python - How does __call__ actually work? -
python's magic method __call__
called whenever attempt call object. cls()()
equal cls.__call__(cls())
.
functions first class objects in python, meaning they're callable objects (using __call__
). however, __call__
function, has __call__
, again has own __call__
, again has own __call__
.
so cls.__call__(cls())
equal cls.__call__.__call__(cls())
, again equilevant cls.__call__.__call__.__call__(cls())
, on , forth.
how infinite loop end? how __call__
execute code?
under hood, calls in python use same mechanism, , arrive @ same c function in cpython implementation. whether object instance of class __call__
method, function (itself object), or builtin object, calls (except optimized special cases) arrive @ function pyobject_call
. c function gets object's type ob_type
field of object's pyobject
struct, , type (another pyobject
struct) gets tp_call
field, function pointer. if tp_call
not null
, calls through that, args , kwargs structures passed pyobject_call
.
when class defines __call__
method, sets tp_call
field appropriately.
here's article explaining of in detail: python internals: how callables work. lists , explains entire pyobject_call
function, isn't big. if want see function in native habitat, it's in objects/abstract.c in cpython repo.
also relevant stackoverflow q&a: what "callable" in python?.
Comments
Post a Comment