3

Is there a way to ignore imported functions in a python module?

When using the following module module.py:

from inspect import getmembers, isfunction
import foo

def boo():
   foo()

def moo():
   pass


funcs = [mem[0] for mem in getmembers(module, isfunction)]

funcs equals : ['boo','moo', 'foo'] (including imported function 'foo')

I want funcs to include ['boo', 'moo'] only.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
rok
  • 9,403
  • 17
  • 70
  • 126
  • See the top answer to [this question](http://stackoverflow.com/questions/5520580/how-do-you-get-all-classes-defined-in-a-module-but-not-imported). It looks like if you filter by `__module__` you can filter out the imports. – Cory Kramer Jul 28 '14 at 12:05
  • 1
    Be warned: modules often have parts of their public API written in and imported from other modules. For example, most of `heapq` actually comes from `_heapq`. – user2357112 Jul 28 '14 at 12:25

1 Answers1

9

You'll have to test for the __module__ attribute; it is a string naming the full module path:

funcs = [mem[0] for mem in getmembers(module, isfunction)
         if mem[1].__module__ == module.__name__]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343