Referring to a module by a string without using eval()

jeanbigboute at gmail.com jeanbigboute at gmail.com
Wed May 17 02:04:55 EDT 2017


I am trying to write some recursive code to explore the methods, classes, functions, builtins, etc. of a package all the way down the hierarchy.  

1) Preliminaries
In [2]: def explore_pkg(pkg):
   ...:     return dir(pkg)
   ...: 

In [3]: import numpy as np

In [4]: l2 = explore_pkg(np.random)

In [5]: len(l2)
Out[5]: 72 # np.random has 72 'things' underneath it

In [6]: l2[0:5]
Out[6]: ['Lock', 'RandomState', '__RandomState_ctor', '__all__', '__builtins__']

2) I ultimately need to create inputs to explore_pkg programmatically en route to a recursively called function.  The only way I can think of is to use strings.  But, passing a string such as 'np.random' into explore_pkg correctly returns the methods/... associated with the string and not the module np.random

e.g. explore_pkg('np.random') will NOT do what I want

explore_pkg(eval('np.random')) does work but I understand eval is dangerous and not to be trifled with.

explore_pkg(getattr(np,'random')) works but if I want to go deeper, I have to nest getattrs.  

Question: Is there a solution to this "turn a string into the module it represents" problem?  I have a vague feeling decorators might be what I need but they've always confused me.

I have searched extensively but couldn't find anything directly related to this.

--- JBB



More information about the Python-list mailing list