Let's say I have B.py
import A
def F():
pass
def G():
pass
if __name__ == '__main__':
A.f()
And when I run it I would like Af
to output list of functions defined in B.py
like this
./B.py
['F', 'G']
The question is what should I write in A.py
?
def f():
???
It seems to be possible because doctest
does something like this.
Update Thank you for your responses, but I forgot to mention one more restriction: I would not like to do import B
in A.py
.
Let me try to explain why: A.py
is a library for runing MapReduce jobs. You just import A
and run some Af
at the vary end of your script. Then Af
analizes what functions you defined and executes them on server. So Af
can not import every module it was called from.
Or can it? Can function know where it was called from?
Update
def f():
module = sys.modules['__main__']
functions = inspect.getmembers(module, inspect.isfunction)
...
def f():
import B
import inspect
functions=inspect.getmembers(B,inspect.isfunction)
http://docs.python.org/library/inspect.html#inspect.getmembers
EDIT
I haven't tried it, but it seems like you could pass the module as an argument to f and use that.
def f(mod):
import inspect
functions=inspect.getmembers(mod,inspect.isfunction)
return functions
Then, from B, you could do something like:
import sys
import A
myfuncs=A.f(sys.modules[__name__])
This is actually pretty easy to do using the dir()
function :
import B
def f():
print(dir(B))
Which gives:
['A', 'F', 'G', '__builtins__', '__cached__', '__doc__', '__file__', '__name__', '__package__']
As you can see, this does include the hidden values that exist in the module that you normally don't see. If you want to be more specific about the things you want, check out the inspect
module .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.