| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
Sorry, something went wrong.
It is set by compiler with the line number of the first line of the class definition.
|
|
||
| * Classes have a new :attr:`!__firstlineno__` attribute, | ||
| populated by the compiler, with the line number of the first line | ||
| of the class definition. |
There was a problem hiding this comment.
If the class has decorators then I think this is the first line of the first decorator. Need a test for this case, and probably to mention in the doc.
Sorry, something went wrong.
There was a problem hiding this comment.
There are existing tests, and they are passed.
I'll add explicit mentioning of this fact, but AFAIK it was not specified for co_firstlineno etc.
Sorry, something went wrong.
Co-authored-by: Mark Shannon <mark@hotpy.org>
|
|
||
| * Classes have a new :attr:`!__firstlineno__` attribute, | ||
| populated by the compiler, with the line number of the first line | ||
| of the class definition. |
There was a problem hiding this comment.
There are existing tests, and they are passed.
I'll add explicit mentioning of this fact, but AFAIK it was not specified for co_firstlineno etc.
Sorry, something went wrong.
|
It is possible to construct classes without __firstlineno__: def f():
__firstlineno__ = 1
class X:
nonlocal __firstlineno__
return X
print(f().__firstlineno__) # AttributeErrorOr: class Y:
global __firstlineno__
print(Y.__firstlineno__) # AttributeErrorThis is obviously an extreme edge case though. You could also do this by manipulating locals() in the class body or the metaclass. Is it worth it to make inspect smarter in the presence of classes without __firstlineno__? File "/Users/jelle/py/cpython/insp.py", line 18, in <module>
print(inspect.findsource(X))
~~~~~~~~~~~~~~~~~~^^^
File "/Users/jelle/py/cpython/Lib/inspect.py", line 1070, in findsource
return lines, object.__firstlineno__ - 1
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'X' has no attribute '__firstlineno__'
|
Sorry, something went wrong.
|
Good point. I thought that it is the same as for __module__ and __qualname__, but it turned out that they are set implicitly in the type constructor even when not specified in the class dict. They are set even for type('A', (), {}). We can try to set __firstlineno__ to the current line number in the top Python frame, but it is safer to not set it at all. Setting __firstlineno__ for classes created by the type() call rather than in the class statement does not help in the only use case for this attribute. I think that for backward compatibility getsource() should convert an AttributeError into OSError which was raised before for classes created by the type() call. |
Sorry, something went wrong.
| Back | FazBrowse Home | New Git URL |
It is set by compiler with the line number of the first line of the class definition.
📚 Documentation preview 📚: https://cpython-previews--118475.org.readthedocs.build/