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.")
$ 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
Bug report
If I run the following program in Python 3.10:
The output is:
The documentation states that
OSErrorcan be raised but does not mentionTypeError.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 ingetsource()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
inspect.getsource()can raiseTypeError#101689inspect.getsource()can raiseTypeError(GH-101689) #102969inspect.getsource()can raiseTypeError(GH-101689) #102970