JFerro
JFerro

Reputation: 3443

How to list all functions in a python module when imported with *

I am importing a module in python as this:

from myutils.user_data import *

How do I find out what are the list of methods that I have imported?

I know one workaround from here:

How to list all functions in a Python module?

being:

from inspect import getmembers, isfunction
import myutils.user_data as module_name
functions_list = getmembers(module_name, isfunction)
print(functions_list)

but this would oblige me to use the nomenclature:

module_name.mehtodA() whereas I would like to be able to use the methods as such methodA()

of course I can do:

from myutils.user_data import *
import myutils.user_data as module_name

but this is actually importing two times.

Any idea?

EDIT: Why do I need this? I am creating documentation for a module in a JupyterHub environment (in premises). I create this documentation using notebooks, i.e. anyone interested in finding out the use of a particular .py file (including utility methods) can open the notebook and play around AND the jupyter notebook can be rendered as a web site with voila. In that case I would like to print all the methods included in the particular .py file.
This is also a question that just made me curious. Someone commented you would never import with * a module. Well, why not if you know what you are importing being a few very small methods.

Upvotes: 2

Views: 5554

Answers (1)

Jakob Stark
Jakob Stark

Reputation: 3855

Generally you are rarely recommended to use the from ... import * style, because it could override local symbols or symbols imported first by other modules.

That beeing said, you could do

symbols_before = dir()
from myutils.user_data import *
symbols_after = dir()
imported_symbols = [s for s in symbols_after if not s in symbols_before]

which stores the freshly imported symbols in the imported_symbols list. Or you could use the fact, that the module is still loaded into sys.modules and do

import sys
from inspect import getmembers, isfunction
from myutils.user_data import *
functions_list = getmembers(sys.modules['myutils.user_data'], isfunction)
print(functions_list)

Upvotes: 4

Related Questions