[Tutor] Getting import to use a variable name
Ben Finney
ben+python at benfinney.id.au
Wed May 20 02:18:11 CEST 2015
"Jim Mooney Py3.4.3winXP" <cybervigilante at gmail.com> writes:
> I can only use the hardcoded imported module name, shutil in this
> case. If I try x = anothermodule, then import x, it doesn't work.
Can you show an example of Python code that you would like to work?
I am *guessing* you mean you want this to work::
>>> foo = 'barmodule'
>>> import foo
That doesn't work because the ‘import’ statement requires the name
directly in the source, not as a string value.
You will be pleased to know of the standard library ‘importlib’
library::
>>> import importlib
>>> foo = 'barmodule'
>>> importlib.import_module(foo)
See the documentation for ‘importlib’ for more on this useful library
<URL:https://docs.python.org/3/library/importlib>.
--
\ “The restriction of knowledge to an elite group destroys the |
`\ spirit of society and leads to its intellectual |
_o__) impoverishment.” —Albert Einstein |
Ben Finney
More information about the Tutor
mailing list