Getting a list of locally-defined functions in python

If I have a script like this:

import sys

def square(x):
    return x*x

def cube(x):
    return x**3

How can I return a list of all the functions defined locally in the program ['square', 'cube'], and not the ones imported.

They are included when I try dir() but so are all the variables and other imported modules. I don't know what to put into dir to refer to the locally executing file.


l = []
for key, value in locals().items():
    if callable(value) and value.__module__ == __name__:
        l.append(key)
print l

So a file with the content:

from os.path import join

def square(x):
    return x*x

def cube(x):
    return x**3

l = []
for key, value in locals().items():
    if callable(value) and value.__module__ == __name__:
        l.append(key)
print l

Prints:

['square', 'cube']

Local scopes also work:

def square(x):
    return x*x

def encapsulated():
    from os.path import join

    def cube(x):
        return x**3

    l = []
    for key, value in locals().items():
        if callable(value) and value.__module__ == __name__:
            l.append(key)
    print l

encapsulated()

Prints out only:

['cube']

Use inspect module:

def is_function_local(object):
    return isinstance(object, types.FunctionType) and object.__module__ == __name__

import sys
print inspect.getmembers(sys.modules[__name__], predicate=is_function_local)

Example:

import inspect
import types
from os.path import join

def square(x):
    return x*x

def cube(x):
    return x**3

def is_local(object):
    return isinstance(object, types.FunctionType) and object.__module__ == __name__

import sys
print [name for name, value in inspect.getmembers(sys.modules[__name__], predicate=is_local)]

prints:

['cube', 'is_local', 'square']

See: no join function imported from os.path.

is_local is here, since it's a function is the current module. You can move it to another module or exclude it manually, or define a lambda instead (as @BartoszKP suggested).