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?
This would allow strings as module names:
import importlib
cred = importlib.import_module('{}_cred'.format(impl))
Where impl is the chosen implementation 'xx' or 'yy'.
Multiple Python libraries use this trick (tornado, rethinkdb...)
Now use like this:
cred.module_var
If you really want the effect of from module import * use:
variables = {name: value for name, value in vars(cred).items()
if not name.startswith('__')}
globals().update(variables)
But import * is not recommended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With