I want to import some package depending on which value the user chooses.
The default is file1.py
:
from files import file1
If user chooses file2
, it should be :
from files import file2
In PHP, I can do this using variable variables:
$file_name = 'file1'; include($$file_name);
$file_name = 'file2'; include($$file_name);
How can I do this in Python?
Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.
__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.
Python doesn't have a feature that's directly equivalent to PHP's "variable variables". To get a "variable variable"'s value (or the value of any other expression) you can use the eval
function.
foo = "Hello World" print eval("foo")
However, this can't be used in an import
statement.
It is possible to use the __import__
function to import using a variable.
package = "os" name = "path" imported = getattr(__import__(package, fromlist=[name]), name)
is equivalent to
from os import path as imported
Old thread, but I needed the answer, so someone else still might...
There's a cleaner way to do this in Python 2.7+:
import importlib my_module = importlib.import_module("package.path.%s" % module_name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With