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?
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.:
though you may want to do more complicated inspect to handle varargs support and the like (e.g. if
__init__is defined withdef __init__(self, *a):, it'll report one parameter, which is technically true, even though it can accept an arbitrary number of positional arguments). TheParameterobjects themselves (the values of the.parametersdictshown in the above example) can tell you more about themselves (so you can distinguish acceptingargfrom accepting*args, or**kwargsor the like).