Tuesday 17 September 2013

Why "import" is implemented this way?

Why "import" is implemented this way?

>>> 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:
1. Why import is implemented this way? Why not let every import math
import a fresh, unmodified copy of math? Why leave the imported math open
to change?
2. Is there any workaround to get math.pi back after doing math.pi =
3(Except math.pi = 3.141592653589793,of course)?
3. Originally I thought import math is preferred over from 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 the import?

No comments:

Post a Comment