0

I am a newbie to python. Below is my module

mymath.py

pi = 3.142

def circle(radius):
    return pi * radius * radius

In terminal, I run it following way:

>>import mymath
>>mymath.pi
>>3.142

When I change pi to a local variable and reload(mymath) and do import mymath, still I get value of mymath.pi as 3.142. However the result of mymath.circle(radius) does reflect the change in result.

def circle(radius):
    pi = 3
    return pi * radius * radius

>>import imp
>>imp.reload(mymath)
>>import mymath
>>mymath.pi
>>3.142
>>circle(3)
>>27

Can anyone tell me what might be the issue?

1 Answer 1

2

From the docs for imp.reload():

When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains.

So when you do imp.reload(mymath), even though pi no longer exists as a global name in the module's code the old definition remains as a part of the updated module.

If you really want to start from scratch, use the following method:

import sys
del sys.modules['mymath']
import mymath

For example:

>>> import os
>>> os.system("echo 'pi = 3.142' > mymath.py")
0
>>> import mymath
>>> mymath.pi
3.142
>>> os.system("echo 'pass' > mymath.py")
0
>>> import sys
>>> del sys.modules['mymath']
>>> import mymath
>>> mymath.pi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pi'
Sign up to request clarification or add additional context in comments.

8 Comments

I am just trying to understand why it is not making the changes even after I removed the pi from global scope and defined it as a local variable. I see the result of circle reflecting the change. However mymath.pi is not reflecting the change. Because in the new code pi is not assigned to 3.142. But instead to 3
@user1247412 Not sure I follow, did you remove the pi = 3.142 line from mymath.py before reloading?
Yes I did remove pi = 3.142
@user1247412 Ahh, I misunderstood the question. See my edit (will add more info shortly).
thank you very much. Is the similar issue exist if I import a module inside other module?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.