Get the source of a class reliably?!?

Chris Angelico rosuav at gmail.com
Tue Apr 30 02:52:49 EDT 2019


On Tue, Apr 30, 2019 at 4:40 PM dieter <dieter at handshake.de> wrote:
>
> "computermaster360 ." <computermaster360 at gmail.com> writes:
>
> > Does anyone have an idea why classes don't contain their definition
> > line number as functions or methods do?
> >
> >>>> some_fun.__code__.co_firstlineno
> > 123
>
> Because classes do not have associated "code" objects.
>
> As you see above, it is not the function itself ("some_fun" in
> your case) that carries the line information but the associated
> "code object" ("some_fun.__code__").
>
> Functions typically are executed several times and
> each execution needs to execute the associated code;
> therefore, functions reference this code.
> There is no specific code directly associated with a class:
> general (i.e. not class specific) code is used to collect
> the operands for the class contruction (i.e. base classes, attribute/method
> definitions), then the class' metaclass is used to really construct
> the class object. Therefore, class objects have no associated "code object".
>

I'm not sure if it'd be of any value to the OP, but a class *does*
have a code object associated with it; it's just that it isn't
retained by the class object after execution. You can see it by
looking at a function that creates a class:

>>> def f():
...     class C:
...             """Attempt 1"""
...     class C:
...             """Attempt 2"""
...     return C
...
>>> f.__code__.co_consts[1]
<code object C at 0x7f2dc41e2540, file "<stdin>", line 2>
>>> f.__code__.co_consts[3]
<code object C at 0x7f2dc41e9ae0, file "<stdin>", line 4>

(If you try this yourself, I would recommend just looking at all of
co_consts, as the exact indices are immaterial.)

I'm not aware of a way to get from a class to the code object that
created it, though, any more than you can (in any general way) get
from a function's return value back to the function that created it.

ChrisA


More information about the Python-list mailing list