Bug report
If I run the following program in Python 3.10:
from dataclasses import dataclass
from inspect import getsource
defs = {}
exec(
"""
@dataclass
class C:
"The source for this class cannot be located."
""",
{"dataclass": dataclass},
defs,
)
try:
getsource(defs["C"])
except OSError:
print("Got the documented exception.")
The output is:
$ python sourceless_dataclass.py
Traceback (most recent call last):
File "<path>/sourceless_dataclass.py", line 16, in <module>
getsource(defs["C"])
File "/usr/lib/python3.10/inspect.py", line 1147, in getsource
lines, lnum = getsourcelines(object)
File "/usr/lib/python3.10/inspect.py", line 1129, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python3.10/inspect.py", line 940, in findsource
file = getsourcefile(object)
File "/usr/lib/python3.10/inspect.py", line 817, in getsourcefile
filename = getfile(object)
File "/usr/lib/python3.10/inspect.py", line 786, in getfile
raise TypeError('{!r} is a built-in class'.format(object))
TypeError: <class 'C'> is a built-in class
The documentation states that OSError can be raised but does not mention TypeError.
The implementation of inspect.getsource() assumes that if a class has no __module__ attribute, it must be a built-in class, but a sourceless dataclass doesn't have a __module__ attribute either. I don't know whether this is a bug in getsource() or whether the generation of the dataclass should set __module__ to '__main__', but in any case the behavior is not as documented.
Your environment
- CPython versions tested on: Python 3.10.6
- Operating system and architecture: Ubuntu Linux 18.04
Linked PRs
Reactions are currently unavailable
Bug report
If I run the following program in Python 3.10:
The output is:
$ python sourceless_dataclass.py Traceback (most recent call last): File "<path>/sourceless_dataclass.py", line 16, in <module> getsource(defs["C"]) File "/usr/lib/python3.10/inspect.py", line 1147, in getsource lines, lnum = getsourcelines(object) File "/usr/lib/python3.10/inspect.py", line 1129, in getsourcelines lines, lnum = findsource(object) File "/usr/lib/python3.10/inspect.py", line 940, in findsource file = getsourcefile(object) File "/usr/lib/python3.10/inspect.py", line 817, in getsourcefile filename = getfile(object) File "/usr/lib/python3.10/inspect.py", line 786, in getfile raise TypeError('{!r} is a built-in class'.format(object)) TypeError: <class 'C'> is a built-in classThe documentation states that OSError can be raised but does not mention TypeError.
The implementation of inspect.getsource() assumes that if a class has no __module__ attribute, it must be a built-in class, but a sourceless dataclass doesn't have a __module__ attribute either. I don't know whether this is a bug in getsource() or whether the generation of the dataclass should set __module__ to '__main__', but in any case the behavior is not as documented.
Your environment
Linked PRs