[Python] Why does inspect fail to get source file for classes in a dynamically-imported module?

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    inspect.getsource() and inspect.getsourcefile() can access source info for a function, but not for a class, when they are in a module that is imported dynamically with importlib.

    Here are two files, thing1.py and thing2.py:


    • thing1.py

      import inspect
      import os
      import importlib.util

      dir_here = os.path.dirname(__file__)
      spec = importlib.util.spec_from_file_location("thing2",
      os.path.join(dir_here, "thing2.py"))
      module = importlib.util.module_from_spec(spec)
      spec.loader.exec_module(module)

      print(module.foo(3))
      print(module.Bar().inc(3))

      print("module source file:", inspect.getsourcefile(module))
      for attr in ['foo','Bar']:
      print("%s source: %s" % (attr, inspect.getsourcefile(getattr(module, attr))))
      print(inspect.getsource(getattr(module, attr)))

    • thing2.py

      def foo(x):
      return x+1

      class Bar(object):
      def inc(self, x):
      return x+1

    If I run test1.py here's what I get:

    > python c:\tmp\python\test2\thing1.py
    4
    4
    module source file: c:\tmp\python\test2\thing2.py
    foo source: c:\tmp\python\test2\thing2.py
    def foo(x):
    return x+1

    Traceback (most recent call last):
    File "c:\tmp\python\test2\thing1.py", line 16, in <module>
    print("%s source: %s" % (attr, inspect.getsourcefile(getattr(module, attr))))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\jason\.conda\envs\py3datalab\Lib\inspect.py", line 940, in getsourcefile
    filename = getfile(object)
    ^^^^^^^^^^^^^^^
    File "C:\Users\jason\.conda\envs\py3datalab\Lib\inspect.py", line 909, in getfile
    raise TypeError('{!r} is a built-in class'.format(object))
    TypeError: <class 'thing2.Bar'> is a built-in class


    I'm using Python 3.11.4.

    Am I missing something during my import step that tells Python how to get source info for classes?

    Continue reading...

Compartilhe esta Página