2

say I have a module like so:

def print_hello(name):
  " prints a greeting "
  print("Hello, {}!".format(name.title()))

I want to set a sys.settrace on my module, so whenever a function from my module is called, it prints a block to stdout, like so

CALLED FUNCTION: say_hello()
Hello, Alex!

Predictably, the trace method will pick up ALL methods which are called, which results in this:

$ python3 trace_example.py
Called function: print_hello
Hello, Alex!
Called function: _remove

How can I tell if a method is in the current module?

(here is my trace function if you were wondering:)

import sys
def tracefunc(frame, event, args):
  if event == 'call':
    print("Called function: {}()".format(frame.f_code.co_name))
sys.settrace(tracefunc)
corvid
  • 10,733
  • 11
  • 61
  • 130
  • Maybe this, using ```inspect``` - [Retrieve module object from stack frame](http://stackoverflow.com/questions/2000861/retrieve-module-object-from-stack-frame) – wwii Dec 02 '14 at 14:45
  • That helps, but still has the problem of the following: print(dir(this_module)) `['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'inspect', 'print_hello', 'sys', 'tracefunc']` Ideally it'd only have `print_hello` and `tracefunc` – corvid Dec 02 '14 at 14:50

1 Answers1

1

You can check the module name of a frame object with:

frame.f_globals['__name__']

Or if you want to check the previous call in the frame stack, (I'm not sure which one is more interesting right now):

frame.f_back.f_globals['__name__']

Of course, note that f_back may be None and that the global dictionary may not have a __name__ member.

UPDATE: If you have a module object and want to list all the top-level callable objects:

callables = [n for n,f in module.__dict__.items() if hasattr(f, '__call__')]

That will get also the types, because technically they look a bit like functions, but you can refine the condition further if you want. (See this other question for extra details.

Community
  • 1
  • 1
rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • that will give the name of the module, but then from that, how would I extract the methods within that module? – corvid Dec 02 '14 at 14:42
  • Your question is _How can I tell if a method is in the current module?_ but the title is _get all methods defined in my own module_. Those are two different questions... which one do you need? – rodrigo Dec 02 '14 at 14:43
  • I need all methods that belong to the current module being called. So this looks pretty close to it, but then I think there needs to be some kind of list comprehension to extract all methods not in builtins. So the end result would look something like: `['print_hello']` in this case, because I only defined one method in module – corvid Dec 02 '14 at 14:44