class DummyInference(Inference): def __init__(self, **kwargs): super(Inference,self).__init__(kwargs) def predicate(self, input: any) -> any: return f"dummy inference with input:{input}" , i encountered the error :python -m worker.worker_test Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/home/ylu/repo/distribute-inference/worker/worker_test.py", line 19, in <module> test_execute() File "/home/ylu/repo/distribute-inference/worker/worker_test.py", line 13, in test_execute model = DummyInference(xxx="tt") ^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ylu/repo/distribute-inference/worker/inference.py", line 11, in __init__ super(Inference,self).__init__(kwargs) TypeError: object.__init__() takes exactly one argument (the instance to initialize), the invoke code is :model = DummyInference(xxx="tt"), what might be the problem

2024-02-27by@Marlboro&@ChatGPT.Model: gpt-4
Marlboro

class DummyInference(Inference):
def init(self, **kwargs):
super(Inference,self).init(kwargs)

def predicate(self, input: any) -> any:
    return f"dummy inference with input:{input}" , i encountered the error :python -m worker.worker_test

Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "/home/ylu/repo/distribute-inference/worker/worker_test.py", line 19, in <module>
test_execute()
File "/home/ylu/repo/distribute-inference/worker/worker_test.py", line 13, in test_execute
model = DummyInference(xxx="tt")
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ylu/repo/distribute-inference/worker/inference.py", line 11, in init
super(Inference,self).init(kwargs)
TypeError: object.init() takes exactly one argument (the instance to initialize), the invoke code is :model = DummyInference(xxx="tt"), what might be the problem

Avatar
Avatar

The issue here is related to the incorrect usage of super() within the __init__ method of the DummyInference class.

When you are calling super(Inference, self).__init__(kwargs), you're trying to initialize the superclass with a dictionary of keyword arguments (kwargs). However, Python's base object class, which is eventually reached by super(), does not accept any arguments besides self in its __init__ method.

To fix this issue, you need to ensure that the __init__ method of the superclass takes the same kind of arguments that you are passing to it. If the superclass Inference is your own class and it is supposed to accept keyword arguments, you need to properly unpack the kwargs when passing them to the super().__init__() call. If Inference does not take any arguments in its __init__ method, you should not pass any.

Here is an example of how you might correct the code:

class DummyInference(Inference):
    def __init__(self, **kwargs):
        # If Inference's __init__ accepts keyword arguments:
        super().__init__(**kwargs)  # Note the `**` to unpack the dict into keyword arguments.

        # If Inference's __init__ does not accept any arguments besides self:
        # super().__init__()  # You would call it like this, without passing kwargs.

    def predicate(self, input: any) -> any:
        return f"dummy inference with input: {input}"

Note that when you are using super(), you don't need to specify the current class and self explicitly, you can just use super().__init__(**kwargs) if the superclass Inference is designed to take keyword arguments.

Please make sure that the Inference class is implemented correctly and accepts the arguments in the way you intended. If Inference is a class from a third-party library, you should check its documentation to see how to properly initialize it.

Marlboro

pls explain the *args and **kwargs usage in Python

Avatar
Avatar

In Python, *args and **kwargs are used to handle variable numbers of arguments in function calls. They allow a function to accept optional arguments, so you can build more flexible APIs. Here's how they work:

  1. *args (Non-Keyword Arguments):

    • *args allows a function to accept any number of positional arguments (arguments that don't have a keyword associated with them).
    • It collects extra positional arguments into a tuple.
    • This is useful when you don't know in advance how many arguments might be passed to your function.

    Example:

    def function_with_args(*args):
        for arg in args:
            print(arg)
    
    function_with_args(1, 2, 3)  # Outputs: 1 2 3
    
  2. **kwargs (Keyword Arguments):

    • **kwargs allows a function to accept any number of keyword arguments (arguments preceded by a keyword and an equals sign).
    • It collects extra keyword arguments into a dictionary where the keys are the argument names and the values are the argument values.
    • This is useful for functions that need to handle named arguments that were not predefined.

    Example:

    def function_with_kwargs(**kwargs):
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    
    function_with_kwargs(first_name="John", last_name="Doe")  # Outputs: first_name: John last_name: Doe
    

You can combine *args and **kwargs in a single function to handle both types of variable arguments:

def function_with_both(*args, **kwargs):
    print("Args:", args)
    print("Kwargs:", kwargs)

function_with_both(1, 2, a=3, b=4)
# Outputs:
# Args: (1, 2)
# Kwargs: {'a': 3, 'b': 4}

When using *args and **kwargs in a function call, they can unpack a sequence or dictionary into separate arguments:

args = (1, 2, 3)
kwargs = {'x': 'foo', 'y': 'bar'}

def function(a, b, c, x, y):
    print(a, b, c, x, y)

function(*args, **kwargs)
# Outputs: 1 2 3 foo bar

Here, *args unpacks the tuple into separate positional arguments, and **kwargs unpacks the dictionary into separate keyword arguments that are passed to the function.

Keep in mind that *args must occur before **kwargs when you are defining a function that accepts both. Similarly, when calling a function, any positional arguments must precede any named arguments.

Marlboro

class Inference:
def init(self, **kwargs):
self.args = kwargs

def predicate(self, input: any) -> any:
    pass

class DummyInference(Inference):
def init(self, **kwargs):
super(Inference,self).init(**kwargs)

def predicate(self, input: any) -> any:
    return f"dummy inference with input:{input}"  , I changed my code as above, and invoke as : model = DummyInference(a="b")
Avatar
Avatar

The updated code still contains a mistake in the super() call within the DummyInference __init__ method. The first argument to super() should be the class itself (DummyInference), not its parent class (Inference). However, when you call super() with no arguments in a class method, Python automatically passes the current class and instance to super() for you. This means you can simply write super().__init__(**kwargs) and Python will correctly resolve it.

Here is the corrected DummyInference class:

class DummyInference(Inference):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)  # Corrected super call

    def predicate(self, input: any) -> any:
        return f"dummy inference with input:{input}"

When you call super() within a method, Python figures out the next class in the method resolution order (MRO) that should be looked up for the method. In this case, it finds the __init__ method of Inference class. Since Inference's __init__ method is designed to accept arbitrary keyword arguments (**kwargs), we ensure the correct behavior by passing the **kwargs from DummyInference's __init__ to Inference's __init__.

Now, when you create an instance of DummyInference with keyword arguments, it should work without errors:

model = DummyInference(a="b")

This will create an instance of DummyInference with an attribute args containing the dictionary {'a': 'b'}.

Marlboro

but i encountered the issue: python -m worker.worker_test
Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "/home/ylu/repo/distribute-inference/worker/worker_test.py", line 19, in <module>
test_execute()
File "/home/ylu/repo/distribute-inference/worker/worker_test.py", line 13, in test_execute
model = DummyInference(a="b")
^^^^^^^^^^^^^^^^^^^^^
File "/home/ylu/repo/distribute-inference/worker/inference.py", line 11, in init
super(Inference,self).init(**kwargs)
TypeError: object.init() takes exactly one argument (the instance to initialize)

Avatar
Avatar

The error message indicates that there is a problem with how super() is being called. The issue is in the super(Inference, self).__init__(**kwargs) line inside your DummyInference class's __init__ method. You are passing the Inference class as the first argument to super(), but you should pass the current class DummyInference instead. However, in most cases, you don't need to pass any arguments to super() in Python 3.

Here's the corrected DummyInference class with the proper super() call:

class DummyInference(Inference):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)  # Corrected super call

    def predicate(self, input: any) -> any:
        return f"dummy inference with input:{input}"

When calling super() in Python 3, you can typically do so without any arguments, and it will automatically determine the context. The call super().__init__(**kwargs) will call the next method in the method resolution order, which is the __init__ method of the Inference class in this case.

To summarize, replace super(Inference, self).__init__(**kwargs) with super().__init__(**kwargs) in your DummyInference class's __init__ method, and that should resolve the issue.

After fixing this, you can create an instance of DummyInference by invoking it with keyword arguments like so:

model = DummyInference(a="b")

This should work without raising a TypeError.

Marlboro

i think it was super(Inference,self).init(**kwargs) caused the problem , is there any diff with super().init(**kwargs)

Avatar
Avatar

Yes, there is a difference between super(Inference, self).__init__(**kwargs) and super().__init__(**kwargs), and using them incorrectly can cause problems.

  1. super(Inference, self).__init__(**kwargs):

    • This is an older syntax that was more commonly used in Python 2, where you explicitly specify the class and the instance when calling super().
    • In this case, you are telling super() to start searching for the next __init__ method in the method resolution order (MRO) from the Inference class.
    • The problem here is that Inference is the base class, so the next class in the MRO would be object, which doesn't accept any additional arguments besides self.
  2. super().__init__(**kwargs):

    • This is the preferred syntax in Python 3. It is cleaner and doesn't require you to explicitly specify the class and the instance.
    • Python automatically determines the context and finds the next method in the MRO from the current class.
    • In your DummyInference class, using super().__init__(**kwargs) correctly calls the Inference class's __init__ method, passing the keyword arguments along.

Here’s an example of how the super() function is typically used in a Python 3 class hierarchy:

class Inference:
    def __init__(self, **kwargs):
        self.args = kwargs
        # ... other initialization ...

class DummyInference(Inference):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)  # Correctly calls Inference.__init__(**kwargs)
        # ... additional initialization ...

    def predicate(self, input: any) -> any:
        return f"dummy inference with input:{input}"

By using super().__init__(**kwargs), you're ensuring that the __init__ method of the parent class (Inference) is called with the keyword arguments, and you avoid the issue of incorrectly invoking the object class's __init__ method, which does not take any additional arguments.