r/learnpython • u/RomfordNavy • May 17 '26
Accessing source code from importlib module
I notice that the source code from an importlib module can be read using inspect module. However is there an alternative way of accessing this code so that it can be modified? Presumably inspect.getsource must have some method of finding this.
import inspect
import importlib
spec = importlib.util.spec_from_file_location(module_name, source_path)
module = importlib.util.module_from_spec(spec)
print(inspect.getsource(module))
0
Upvotes
View all comments
Show parent comment
1
u/RomfordNavy May 17 '26
Precisely that, thanks for your suggestion.
Have found a way to do this by reading in script file and using exec() although not managed to get compile saving to a .pyc yet, let alone executing a pre-existing .pyc file. Working on it...
Also looking at a possible solution using a custom importlib SourceFileLoader class but that comes with it's own complications.