0

Let's say I have a file called example.py with the following content:

def func_one(a):
    return 1

def func_two(b):
    return 2

def func_three(b):
    return 3

How would I get a list of function instances for that file? I have tried playing with the compiler,parser and ast modules but I can't really figure it out. It might be a lot easier than that, but it's slightly out of my depth.

EDIT: To be clear I don't want to import the functions.

Glen Robertson
  • 1,177
  • 8
  • 10

4 Answers4

4

You can use inspect module:

>>> import inspect
>>> import example
>>> inspect.getmembers(example, inspect.isroutine)
[('func_one', <function func_one at 0x0238CBB0>), ('func_three', <functi
three at 0x0240ADB0>), ('func_two', <function func_two at 0x0240ADF0>)]
Mikhail Churbanov
  • 4,436
  • 1
  • 28
  • 36
0

You can use dir. This return the list of names in the current local scope. Although this might return more than function names.

>>> import utils
>>> utils.__name__
'utils'
>>> dir(utils)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'human_number', 'islice', 'math', 'prime_factors', 'primes_sieve', 'primes_sieve1', 'proper_divisors', 'pyth_triplet', 'square_of_sum', 'sum_of_nums', 'sum_of_squares', 'test', 'triangle_nums', 'window']
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
0

If you really don't want to import into the namespace like this:

import examples
print dir(examples)

['__builtins__', '__doc__', '__file__', '__name__', 
'__package__', 'func_one', 'func_three', 'func_two'] #OUTPUT

You could open and read the file, doing a search for any defs and append those to a list, thus returning all function, and method definition names.

fraxel
  • 34,470
  • 11
  • 98
  • 102
0

You could use globals() function, it is return a dict with all global environment where you can find you functions. Example:

d = globals().copy()
l = []
[l.append(k) for k in d if k.startswith('func')]
Denis
  • 7,127
  • 8
  • 37
  • 58