Updating an Imported Function

Diez B. Roggisch deets at nospam.web.de
Thu May 7 20:25:56 CEST 2009


Donovan Parks schrieb:
> Hello,
> 
> I'm new to Python and have what is probably a very basic question. I
> am writing a helloWorld() function within a file called helloWorld.py:
> 
> def helloWorld():
> 	print 'hi'
> 
> Now, I can import and run this function:
> 
> import helloWorld
> helloWorld.helloWorld()
> 
> Which will print 'hi' as expected. Now, I'd like to update this
> function in my text editor so it is:
> 
> def helloWorld():
> 	print 'hello world'
> 
> Without having to exit my Python interpreter, how can I import this
> revised function? If I do the import again:
> 
> import helloWorld
> 
> And run helloWorld.helloWorld() it will still print out just 'hi'.
> I've tried deleting this function (a weird concept to me as I come
> from a C++ background) using del helloWorld and than importing again,
> but the function will still print out just 'hi'.
> 
> Can this be done? How so?

reload(helloWorld)

But there are some caveats, and IMHO reloading isn't worth the trouble - 
it is *so* easy to write a second script, test.py or whatever, that  you 
just call from a shell. And this has the added benefit that you can 
create even somewhat more elaborate toy-code.

If one wants to play around with objects created, either do

python -i test.py

or try to use pdb, the python debugger, through

import pdb; pdb.set_trace()

to get an interactive prompt at whatever point you want.

Diez



More information about the Python-list mailing list