Why class constructor doesn't have attribute __code__?

646 Views Asked by At

I have simple python3 class:

class A:
    def foo(self):
    pass

print(A.foo.__code__.co_argcount)
print(A.__init__.__code__.co_argcount)

OUTPUT will be:

1
AttributeError: 'wrapper_descriptor' object has no attribute '__code__'

Can I cast class constructor or do something else in order to count number of arguments in this constructor?

1

There are 1 best solutions below

0
ShadowRanger On

Since you didn't define a __init__ yourself, A.__init__ is (at least on the CPython reference interpreter) a C-level default __init__ function, not a Python level function at all. __code__ is the compiled bytecode of a Python level function; if the function isn't defined at the Python level, it doesn't have bytecode in the first place.

If you're just trying to count the number of parameters to the constructor, the function signature will tell you, e.g.:

>>> import inspect
>>> len(inspect.signature(A).parameters)
0

though you may want to do more complicated inspect to handle varargs support and the like (e.g. if __init__ is defined with def __init__(self, *a):, it'll report one parameter, which is technically true, even though it can accept an arbitrary number of positional arguments). The Parameter objects themselves (the values of the .parameters dict shown in the above example) can tell you more about themselves (so you can distinguish accepting arg from accepting *args, or **kwargs or the like).