Reputation: 1573
If I do something like
import my_import
from my_import import *
I can change variables in the import by doing something like
my_import.k = 6
If I wanted to change the value of k for every single import I used, is there a way for me to iterate over all imports and set the value of k in each?
Essentially I'm looking for something like
for each x in [list of imports]
x.k = 6
Upvotes: 0
Views: 6323
Reputation: 328
If you just wanna change the attribute value of the imported module objects, you may try this code using function __import__()
and map()
:
#__import__() & map()
In [1]: moduleNames = ['my_import1', 'my_import2', 'my_import3']
In [2]: for module in map(__import__, moduleNames):
...: module.k = 1000
...:
And you can check the result by import this modules one by one, and output the k:
In [3]: import my_import1, my_import2, my_import3
In [4]: print my_import1.k
1000
In [5]: print my_import2.k
1000
In [6]: print my_import3.k
1000
Actually, you can change the map() function into a List Comprehension or a Generator, and the code would be much resemble your demanding code-style:
#List Comprehension
In [7]: for module in [__import__(m) for m in moduleNames]:
...: module.k = 2000
...:
In [8]: print my_import1.k
2000
In [9]: print my_import2.k
2000
In [10]: print my_import3.k
2000
In [11]:
#Generator
In [11]: for module in (__import__(m) for m in moduleNames):
....: module.k = 3000
....:
In [12]: print my_import1.k
3000
In [13]: print my_import2.k
3000
In [14]: print my_import3.k
3000
In [15]:
BTW, the list comprehension and generator are quite similar, though. Generator is much more recommended when you have a large number of modules to deal with and no need to import them all at one time. It's more efficient and memory-saving.
Upvotes: 1
Reputation: 3457
There's some reasons to want this, but it's a dangerous game.
import my_import1
import my_import2
import my_import3
import sys
# Check if you don't believe me
print(my_import1.x)
print(my_import2.x)
print(my_import3.x)
# Grab the interesection of all loaded modules and globals in this scope
allmodules = [sys.modules[name] for name in set(sys.modules)&set(globals())]
for module in allmodules:
module.x = 10000
# Check if you don't believe me
print(my_import1.x)
print(my_import2.x)
print(my_import3.x)
Output:
1
2
3
10000
10000
10000
The caveat with this is that it will grab 'sys' as well and alter it. Perhaps add a check for "built-in" in the module key name.
Upvotes: 2