When I load the source code of a class from a module directly, it's fine:
import arg_master
inspect.getsource(func)
When I load a module with
spec_from_file_location
and go for a function it's fine.When I load a module with
spec_from_file_location
and go for a class, it fails with:TypeError: <class 'mymod.ArgMaster'> is a built-in class
(it's not. I wrote it.)
Here is my full source:
import os, inspect, importlib
filename = 'arg_master.py'
spec = importlib.util.spec_from_file_location("mymod", filename)
mymod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mymod)
func = vars(mymod)['ArgMaster']
inspect.getsource(func) #<<< Fails
Load method number 2 also fails:
import importlib, types
filename = 'arg_master.py'
loader = importlib.machinery.SourceFileLoader('mod', filename)
mod = types.ModuleType(loader.name)
loader.exec_module(mod)
func = vars(mod)['ArgMaster']
inspect.getsource(func)
Edit: I found a hackish solution:
import inspect
filename = 'arg_master.py'
name = os.path.basename(filename)
name = os.path.splitext(name)[0]
importlib.import_module(name)
func = vars(mod)['ArgMaster']
inspect.getsource(func)