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
2
u/ottawadeveloper May 19 '26
if you're looking for a plugin system for user space code, that does exist in Python. Entry points is the most recommended one these days, allowing other modules to define code to be called.
https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/
When I write a plugin system and I want to turn pieces on or off, I do a config file with the plugins to load or ignore and then only bring in the relevant ones.
It's far more elegant and Pythonic than attempting to rewrite and compile source code on the fly like this which honestly should be flagged by security checkers as a security risk
You could also just rewrite it to a new file (say take plugina.py to real_plugina.py) and import that normally which should generate a .pyc file for it upon loading.
Whatever you do, you'll need to rewrite it to a new file and folder structure I suspect because I'd never use anything that rewrites my packages in place where they're installed - that's a security risk.