This questions is related global-scope of python.
There are have two files below.
fileA.py
import pprint
pprint.pprint(globals())
fileB.py
import fileA
def global_funcB():
return "global_funcB"
When I run python fileB.py
. The globals() of fileA.py only contains fileA's content.
Is that possible to get address of global_funcB
in fileB.py from fileA.py? So far, I only can do this from fileB.py.
Note: for my purpose, there is no way to import fileB from fileA.py
[Edit]
Let me describe my purpose clearly.
loader.py
class loader(object):
def __init__(self, module):
print(dir(module))
builder.py + class function
import loader
class someobj(object):
def somefunc(self):
pass
loader.loader(someobj)
If I passing some module/class from fileB to build fileA, then it's possible to fetch function of fileB.
However, if the function in builder.py is globally.
builder.py + global function
import loader
def someglobalfunc(self):
pass
loader.loader(???)
I have no idea how to pass globals() as a module/class to another file.
If you want to get the globals of file B
inside file A
after importing it in B
and use the globals in B
it's completely redundant, as you can simple get the globals within B
and use them.
If you want to get those globals and use them with A
it's not possible because at the time you are running the file A
there is not B
in it's name space which is completely obvious.
Based on your edit:
If you are going to pass multiple global function to loader
you can find all functions within your global namespace and pass them to loader
. For example you can look for objects that have a __call__
attribute (if your classes and other objects are not callable). Or as a more general way use types.FunctionType
.
from typing import FunctionType
functions = [obj for obj in globals().values() if isinstance(obj, FunctionType)]
The loader class:
class loader:
def __init__(self, *modules):
for module in modules:
print(dir(module))
Your executable file:
import loader
from typing import FunctionType
def someglobalfunc1(self):
pass
def someglobalfunc2(self):
pass
functions = [obj for obj in globals().values() if isinstance(obj, FunctionType)]
loader.loader(*functions)