[issue32313] Wrong inspect.getsource for datetime

Paul Ganssle report at bugs.python.org
Sun Sep 16 13:42:53 EDT 2018


Paul Ganssle <p.ganssle at gmail.com> added the comment:

I think this is *mostly* the correct behavior (though it may indeed be confusing). Note that `datetime.py` *is* the source of the module `datetime`, it's just that most of the code in there is shadowed by the line you've linked.

If you try and get the source of individual methods that were imported from `_datetime`, you'll get the expected failure:

>>> inspect.getsource(datetime.datetime.fromisoformat)
-- Long traceback --
TypeError: module, class, method, function, traceback, frame, or code object was expected, got builtin_function_or_method


That said, `inspect.getsource` does seem to be erroneously using the Python source for classes, e.g. `print(inspect.getsource(datetime.date))`

This is consistent with the behavior of `functools`, where the Python code for `functools.partial`, even when the C implementation is used.

Not sure if this is something that should be a warning, an exception or if the behavior should simply be documented in the `inspect` documentation.

I'll note that both `inspect.getsource(datetime)` and `inspect.getsource(datetime.date)` were IOError exceptions in Python 2.7, but have been returning the Python source code since at least Python 3.4.

----------
components: +Library (Lib)
nosy: +belopolsky, yselivanov
type:  -> behavior
versions: +Python 3.4, Python 3.5, Python 3.6, Python 3.7, Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32313>
_______________________________________


More information about the Python-bugs-list mailing list