Reputation: 1177
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.
Upvotes: 0
Views: 183
Reputation: 35269
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 def
s and append those to a list, thus returning all function, and method definition names.
Upvotes: 0
Reputation: 7343
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')]
Upvotes: 0
Reputation: 4500
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>)]
Upvotes: 4
Reputation: 73588
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']
Upvotes: 0