pyc file [Newbie Question]

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Apr 3 03:08:34 EDT 2007


On Mon, 02 Apr 2007 23:44:41 -0700, Jim Aikin wrote:

> Working through the tutorial, I created a file called fibo.py in my text 
> editor, and imported it into Idle. It worked as expected. I then edited the 
> file and resaved it. I used del fibo, followed by import fibo.

That probably won't cause a full re-import. del fibo will only delete the
reference called "fibo". The underlying module object will still exist
until it is garbage-collected. It will only be garbage-collected if it
isn't being used. Chances are, the module *is* being used somewhere, so
when you call "import fibo" the import machinery simply gives you a new
reference to the old module object.

The correct way to do what you want is to simply say "reload(fibo)".

But don't forget that any old objects from the module will NOT pick up the
new behaviour. They will keep their old behaviour, so after a reload() you
have to recreate all the objects you created.

For example:


import fibo # imports the module as it exists *now*
x = fibo.SomeClass()
# x is an instance defined in fibo

# now edit the fibo module and change the behaviour of SomeClass

reload(fibo)

# now the module fibo has picked up the new behaviour
# but the object x still has the code belonging to the OLD module
x = fibo.SomeClass() # recreate x with new code


[snip]
 
> One point of possible confusion here is in the line in the following 
> paragraph of 6.1.2, "Whenever spam.py is successfully compiled...." My 
> question is, is it compiled when being imported? I didn't spot any mention 
> in the Tutorial of when or how a .py file might be (or would automatically 
> be) compiled, so I'm assuming that it's automatically compiled while being 
> imported. If this is a bad assumption, then maybe it's the root of my 
> misunderstanding. Maybe I have to _do_ something to fibo.py in order to 
> create a new version of fibo.pyc.

Just import it, or reload().


-- 
Steven D'Aprano 




More information about the Python-list mailing list