0

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 A.f 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 A.f at the vary end of your script. Then A.f analizes what functions you defined and executes them on server. So A.f 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)
    ...
alexanderkuk
  • 1,551
  • 2
  • 12
  • 29
  • 2
    possible duplicate of [Find functions explicitly defined in a module (python)](http://stackoverflow.com/questions/1106840/find-functions-explicitly-defined-in-a-module-python) – kennytm May 01 '12 at 18:36

2 Answers2

3
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__])
mgilson
  • 300,191
  • 65
  • 633
  • 696
2

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.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183