Search code examples
pythonmodulepyc

Python class can't be updated after being compiled


I just started with python a couple of days ago, coming from a C++ background. When I write a class, call it by a script, and afterwards update the interface of the class, I get some behaviour I find very unintuitive.

Once successfully compiled, the class seems to be not changeable anymore. Here an example:

testModule.py:

class testClass:
    def __init__(self,_A):
        self.First=_A

    def Method(self, X, Y):
        print X

testScript.py:

import testModule

tm=testModuleB.testClass(10)
tm.Method(3, 4)

Execution gives me

3

Now I change the argument list of Method:

def Method(self, X):

, I delete the testModule.pyc and in my script I call

tm.Method(3)

As result, I get

TypeError: Method() takes exactly 3 arguments (2 given)

What am I doing wrong? Why does the script not use the updated version of the class? I use the Canopy editor but I saw this behaviour also with the python.exe interpreter.

And apologies, if something similar was asked before. I did not find a question related to this one.


Solution

  • Python loads the code objects into memory; the class statement is executed when a file is first imported an a class object is created and stored in the module namespace. Subsequent imports re-use the already created objects.

    The .pyc file is only used the next time the module is imported for the first time that Python session. Replacing the file will not result in a module reload.

    You can use the reload() function to force Python to replace an already-loaded module with fresh code from disk. Note that any and all other direct references to a class are not replaced; an instance of the testClass class (tm in your case) would still reference the old class object.

    When developing code, it is often just easier to restart the Python interpreter and start afresh. That way you don't have to worry about hunting down all direct references and replacing those, for example.