Referring to a module by a string without using eval()
Andre Müller
gbs.deadeye at gmail.com
Wed May 17 05:06:15 EDT 2017
Peter Otten <__peter__ at web.de> schrieb am Mi., 17. Mai 2017 um 09:31 Uhr:
> jeanbigboute at gmail.com wrote:
>
> > 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.
>
> > 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.
>
Hello,
with a Class you can do it also.
import os
class Module:
def __init__(self, module):
self._name = module.__name__
print('Got module', self._name)
self._file = module.__file__ if hasattr(module, '__file__') else
'(built-in)'
self._module = module
def __repr__(self):
return "<module '{}' from '{}'>".format(self._name, self._file)
def __getattr__(self, key):
ret = getattr(self._module, key)
if isinstance(ret, types.ModuleType):
print('Attribute {} is in the module {}'.format(key,
self._name))
return Module(ret)
else:
print('Attribute {} is not a module. It\'s a {}'.format(key,
type(ret)))
return ret
def __getitem__(self, key):
return self.__getattr__(key)
os_wrapped = Module(os)
sub1 = 'path'
sub2 = 'sys'
sub3 = 'version'
value = os_wrapped[sub1][sub2][sub3]
print(value)
Maybe this code breaks other stuff. Also error handling is not present.
Greetings Andre
More information about the Python-list
mailing list