TypeError: object () takes no parameters - but only in Python 3

I am porting some code from Python 2 to Python 3 and I have a different behavior. Examining the โ€œwhat changedโ€ lists did not indicate any significant differences, but apparently I missed the big one.

I simplified my code as much as possible in order to get this "minimal malfunctioning program":

def decorator(Type): """ This is a class decorator. It replaces a class with a subclass which *should be* equivalent. The result works on Python 2.7 but not on Python 3.4. """ class FactorySubclass(Type): """ This subclasses from the provided type, and overrides the __new__ and __init__ methods, but replaces them with exact equivalents, so I can't see how this has any effect. """ def __new__(cls, *args, **kwargs): # Simplified this code to do basically nothing. # If this line is removed, it works on both versions. return Type.__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): # Simplified this code to do basically nothing. Type.__init__(self, *args, **kwargs) return FactorySubclass @decorator class ExampleClass(object): def __init__(self, param=3): print("Constructed example instance") ec = ExampleClass(param=5) 

This code runs and prints a Constructed example instance in Python 2.7. This code crashes and removes the stack trace in Python 3.4.

 Traceback (most recent call last): File "mfp.py", line 31, in <module> ec = ExampleClass(param=5) File "mfp.py", line 16, in __new__ return Type.__new__(cls, *args, **kwargs) TypeError: object() takes no parameters 

Usually this error means that someone has a __init__ error (and therefore the constructor parameters bypass the corresponding class and are assigned to the constructor without parameters without object , but this does not look like this here.

Oh, and as an afterthought, I confirmed that yes, the param value was 5 in Python 2.7.

2to3 gives him a clean health score.

Please give me a pointer to a change in Python 3, which will invalidate this code, so I can learn more about it.

+6
source share
1 answer

You have an answer in your question:

Usually this error means that [...] the parameters of the constructor [...] are passed to the object-parametric constructor [...]

To fix, change your decorator only to add __init__ and __new__ if the past one in Type has these methods.

+2
source

Source: https://habr.com/ru/post/977472/


All Articles