I want to modify a module xyz and its functions like that:
def modify(fun): modulename = fun.__module__ # this is string. ok, but not enough import xyz modify(xzy.test)
My problem is how to access the namespace of xzy
inside modify
. Sometimes
globals()[fun.__module__]
works. But then I get problems if the definition modify
is in a different file than the rest of the code.
Modules can define functions, classes, and variables that you can reference in other Python . py files or via the Python command line interpreter. In Python, modules are accessed by using the import statement.
A module can find out its own module name by looking at the predefined global variable __name__.
We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.
The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script.
Use the inspect module:
import inspect def modify(fun): module = inspect.getmodule(fun)
This is the same as polling the module from sys.modules
using fun.__module__
. Although getmodule
tries harder even if fun
does not have a __module__
attribute.
You want to get the module object from its name? Look it up in the sys.modules
dictionary that contains all currently loaded modules:
import sys def modify(func): module = sys.modules[func.__module__]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With