def demo_func(*args, **kwargs):
pass
def test_locals(*args, **kwargs):
"Test whether we can get the local functions using locals()"
def local_demo_func(self, *args, **kwargs):
pass
return locals()['local_demo_func'] == local_demo_func
# `globals()` returns a dictionary with the global symbol table:
assert globals()['demo_func'] == demo_func
# `locals()` returns a dictionary with the current local symbol table
assert test_locals()
Get Function from Modules Using Its Name
Python
How to get the function defined in the current module using its name.
Sometimes we need to obtain a function defined in a certain module using its name. If the function you are calling is defined in the same module, we can use globals()
or locals()
:
globals()
returns a dictionary with the global symbol table:locals()
returns a dictionary with the current local symbol table:
If it’s defined another module, we can simply do
For example: