Alex Rivera | Logout

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

Asked 2011-07-13T10:22:55.353
54

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?

Edit
Report

1 Answer

46

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)
answered 2013-05-07T16:28:11.507

Your Answer