How do I import variable packages in Python like using variable variables ($$) in PHP?

Viewed 50434

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?

5 Answers

Basing myself on mattjbray's answer:

from importlib import import_module

# lookup in a set is in constant time
safe_names = {"file1.py", "file2.py", "file3.py", ...}

user_input = ...

if user_input in safe_names:
    file = import_module(user_input)
else:
    print("Nope, not doing this.")

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.

Related