6

Is there a method to find all functions that were defined in a python environment?

For instance, if I had

def test:
   pass

some_command_here would return test

0

5 Answers 5

6

You can use inspect module:

import inspect
import sys


def test():
    pass

functions = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isfunction)]
print functions

prints:

['test']
Sign up to request clarification or add additional context in comments.

1 Comment

Definitely the nicest way proposed so far +1
4

You can use globals() to grab everything defined in the global scope of the file, and inspect to filter the objects you care about.

[ f for f in globals().values() if inspect.isfunction(f) ]

Comments

2

Use globals() and types.FunctionType

>>> from types import FunctionType
>>> functions = [x for x in globals().values() if isinstance( x, FunctionType)]

Demo:

from types import FunctionType
def func():pass
print [x for x in globals().values() if isinstance(x, FunctionType)]
#[<function func at 0xb74d795c>]

#to return just name
print [x for x in globals().keys() if isinstance(globals()[x], FunctionType)]
#['func']

Comments

1
>>> def test():
...     pass
...
>>> [k for k, v in globals().items() if callable(v)]
['test']

Comments

1

First, we will create the test function we want to find.

def test():
    pass

Next, we will create the some_command_here function that you want.

def some_command_here():
    return filter(callable, globals().values())

Finally, we call the new function and convert the filter into a tuple for viewing.

tuple(some_command_here())

Note: This searches the current global namespace and returns anything callable (not just functions).


Example:

>>> def test():
    pass

>>> def some_command_here():
    return filter(callable, globals().values())

>>> tuple(some_command_here())
(<function test at 0x02F78660>,
 <class '_frozen_importlib.BuiltinImporter'>,
 <function some_command_here at 0x02FAFDF8>)
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.