Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find functions explicitly defined in a module (python)

Tags:

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?

like image 577
Cory Avatar asked Jul 09 '09 22:07

Cory


People also ask

How do I see all the functions in a Python module?

We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.

What is function defined in module in Python?

The word “function” has different meanings in mathematics and programming. In programming it refers to a named sequence of operations that perform a computation. For example, the function sqrt() which is defined in the math module computes the square root of a given value: In [1]: from math import sqrt sqrt(4)

Which library function returns the list of all functions in a module?

dir() is a built-in function that also returns the list of all attributes and functions in a module.

How do you call a function from a module in Python?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.


2 Answers

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).

like image 175
ars Avatar answered Oct 03 '22 06:10

ars


How about the following:

grep ^def my_module.py 
like image 42
David Locke Avatar answered Oct 03 '22 07:10

David Locke