Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 958
skargor Avatar asked Jul 13 '11 10:07

skargor


People also ask

How do you import a package 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.

What is __ import __ in Python?

__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.


2 Answers

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 
like image 145
Jeremy Avatar answered Oct 08 '22 23:10

Jeremy


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) 
like image 44
Dan Copeland Avatar answered Oct 08 '22 23:10

Dan Copeland