Search code examples
pythonpython-3.xintsys

Is int() a standalone function or it is actually an _init_ constructor method of the int class under covers?


(a) I am trying to figure out whether int(), float(), tuple() and similar functions are standalone functons or they work like constructors for user classes (i.e. invoking class __init__() method under covers.)

(b) I wanted to find available signatures of these methods, like int(str), int(str, base).

(c) I tried peeking into the source code on github, but it seems to be implemented on the c-layer, not on Python-layer. There is even no header-like stub Python code for this.


Solution

  • Yes, all of those are classes, they are class objects. Their type is type (which itself, is a class, a metaclass):

    >>> type(int)
    <class 'type'>
    

    Same as a custom class:

    >>> class Foo: pass
    ...
    >>> type(Foo)
    <class 'type'>
    

    And seemingly paradoxically:

    >>> type(type)
    <class 'type'>
    

    NOTE: None of these objects are the __init__. That is a special method that gets called by the constructor to run custom initialization. IOW:

    >>> Foo.__init__ is Foo
    False