+ 10
How to import module if the module-name is stored in a variable?
I have created the following example https://code.sololearn.com/cmiA9TFuq6Mx/?ref=app , but though it displays that all wanted modules were imported successfully, the access to math.pi fails. What do I have to change in the program to get it working?
11 ответов
+ 6
Adding:
globals()[i] = new_module
after:
new_module = __import__(i)
also works, because this makes the dynamic import available in the global namespace.
+ 7
HonFu you are right.
def tst():
from math import sqrt
print(f'{sqrt(16)}') # <- OK
tst()
print(f'{sqrt(16)}') # <- fails "sqrt not defined"
So it's possible to import a module in a function, but you can not access it from main program.
+ 5
For now I've only glanced at it, but isn't the problem that the name you give your import is lost after the function ends?
You import different modules, but not under their names, but under the alias new_module which is overwritten each time.
And this one name belongs to the function locally.
EDIT:
You can import normally in a function, but the names will again be bound locally, and other functions won't know about it.
You can do it like this:
global math, collections, textwrap
import math, collections, textwrap
Now you declared that the names should be bound globally, and then, you will afterwards be able to use them in the other functions.
You can also use your variable style - just globalize the name first.
Better to import globally in the first place.
Imagine your teammate has defined an important variable math. Now she imports your function, and her math is overwritten and she doesn't even know.
+ 5
Okay, then this:
def f():
x = __import__('random')
print(x.randint(1, 10))
f()
(Sorry, I'm not sure if you already figured it out.)
+ 5
HonFu it works ^^", I imported it with exec(), which didn't work unless I added an extra parameter, sorry!
+ 4
With some research, I founs out that __module__ is used for python 2.6 and lower. In python 3, you can simply import module with exec:
exec('import module_name')
But for some reason that I still don't know (I know now), import doesn't work inside functions, but you can make it work with this:
exec('import module_name', globals())
Here is the modified version of your code:
https://code.sololearn.com/cPpi1DorpOAA/?ref=app
EDIT:
it seems that __module__ also works perfectly with python3, I just used it the wrong way.
+ 4
Aymane Boukrouh, try this:
def f():
import random
print(random.randint(1,10))
f()
+ 4
HonFu I'm not talking about normal import, the question says import from a string, which for me only worked outside functions.
+ 3
Thank You all for Your answers. After following the suggestion of Manuel Maier the code https://code.sololearn.com/cK33d82UQeG1/?ref=app works as intended.
0
llkɣɣq😃0?