I am running several python scripts that are exactly the same except for a prefix on the variables. (Just for clarity, I am working with Tweepy and the Twitter API).
I have named each API credential xx_apicred.py
, yy_apicred.py
, etc, and these are saved as a separate file in the folder.
Also, I have tables named xx_info
, yy_info
, etc. This part is easy to change through string manipulation.
I would like to change this so that it is one file where I pass the xx string as an argument. This works for everything except the from xx_cred import*
When I replace it with a string variable, I get the error that ImportError: No module named 'var'
Is there a way I can import through a variable?
3
Answers
This would allow strings as module names:
Where
impl
is the chosen implementation'xx'
or'yy'
.Multiple Python libraries use this trick (tornado, rethinkdb…)
Now use like this:
If you really want the effect of
from module import *
use:But
import *
is not recommended.extra FYI only not to be chosen as best answer
This is how rethink DB does internally, based on which loop type the user sets:
imp
is a useful python library you can leverage as well.First of all, let me note that
from module import *
is generally considered bad practice in actual code. It’s really just a trick to make interpreter sessions easier. You should eitherfrom module import a, b
orimport module; module.a()
.If you REALLY want to dynamically bring all names in the module into the current global namespace, you can do this:
This will work and let you use members of
module
unqualified but tools such as IDEs will not understand this magic and will think that your variables are undefined (not that this will stop the code from running, there’ll just be highlighted ‘errors’). You would be much better off manually creating the variables you need as aliases of the qualified versions as others have mentioned, e.g.variable = cred.variable
.