Cory
Cory

Reputation: 24340

Find functions explicitly defined in a module (python)

Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:

from datetime import date, datetime

def test():
    return "This is a real method"

Even if i use inspect() to filter out the builtins, I'm still left with anything that was imported. E.g I'll see:

['date', 'datetime', 'test']

Is there any way to exclude imports? Or another way to find out what's defined in a module?

Upvotes: 24

Views: 10416

Answers (6)

pgov
pgov

Reputation: 21

import inspect, sys

def get_module_func(module):
    is_function_in_module = lambda obj: inspect.isfunction(obj) and inspect.getmodule(obj) == module
    return inspect.getmembers(module, is_function_in_module)

get_module_func(sys.modules[__name__])

Upvotes: 0

Stefano Borini
Stefano Borini

Reputation: 143935

Every class in python has a __module__ attribute. You can use its value to perform filtering. Take a look at example 6.14 in dive into python

Upvotes: 1

ars
ars

Reputation: 123588

Are you looking for something like this?

import sys, inspect

def is_mod_function(mod, func):
    return inspect.isfunction(func) and inspect.getmodule(func) == mod

def list_functions(mod):
    return [func.__name__ for func in mod.__dict__.itervalues() 
            if is_mod_function(mod, func)]


print 'functions in current module:\n', list_functions(sys.modules[__name__])
print 'functions in inspect module:\n', list_functions(inspect)

EDIT: Changed variable names from 'meth' to 'func' to avoid confusion (we're dealing with functions, not methods, here).

Upvotes: 32

Sergey Konozenko
Sergey Konozenko

Reputation: 41

You can check __module__ attribute of the function in question. I say "function" because a method belongs to a class usually ;-).

BTW, a class actually also has __module__ attribute.

Upvotes: 2

David Locke
David Locke

Reputation: 18084

How about the following:

grep ^def my_module.py

Upvotes: 5

Ian P
Ian P

Reputation: 1533

the python inspect module is probably what you're looking for here.

import inspect
if inspect.ismethod(methodInQuestion):
    pass # It's a method

Upvotes: 0

Related Questions