PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 27, 2022

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

 November 27, 2022     import, methods, module, python     No comments   

Issue

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.


Solution

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)


Answered By - Jakob Stark
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing