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?
Old thread, but I needed the answer, so someone else still might...
There's a cleaner way to do this in Python 2.7+:
As Fredrik Lundh states:
And by the way that's the last one method that you're intrested in.
Simply write (for example):
Basing myself on
mattjbray
's answer:Saves a few lines of code, and allows you to set
safe_names
programmatically, or load multiple modules and assign them to a dict, for example.It's probably a very bad idea to let the user choose what to import. Packages can execute code on import, so you're effectively allowing a user to arbitrarily execute code on your system! Much safer to do something like
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.However, this can't be used in an
import
statement.It is possible to use the
__import__
function to import using a variable.is equivalent to