>>> import math >>> math.pi 3.141592653589793 >>> math.pi = 3 >>> math.pi 3 >>> import math >>> math.pi 3 Initial question: Why can't I get math.pi back?
I thought import would import all the defined variables and functions to the current scope. And if a variable name already exists in current scope, then it would replace it.
Yes, it does replace it:
>>> pi = 3 >>> from math import * >>> pi 3.141592653589793 Then I thought maybe the math.pi = 3 assignment actually changed the property in the math class(or is it math module?), which the import math imported.
I was right:
>>> import math >>> math.pi 3.141592653589793 >>> math.pi = 3 >>> from math import * >>> pi 3 So, it seems that:
If you do import x, then it imports x as a class-like thing. And if you make changes to x.property, the change would persist in the module so that every time you import it again, it's a modified version.
Real question:
- Why is
importimplemented this way? Why not let everyimport mathimport a fresh, unmodified copy ofmath? Why leave the importedmathopen to change? - Is there any workaround to get
math.piback after doingmath.pi = 3(exceptmath.pi = 3.141592653589793, of course)? - Originally I thought
import mathis preferred overfrom math import *. But this behaviour leaves me worrying someone else might be modifying my imported module if I do it this way...How should I do theimport?