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?

4

1 回答 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'
于 2013-03-29T18:27:16.520 回答