views:

37

answers:

2

Hey,

At my work place there is a script (kind of automation system) that loads and runs our application tests from an XML file.

In the middle of the process the script calls __import__(testModule) which loads the module from its file.

The problem starts when I tried adding a feature by dynamically adding functions to the testModule at runtime.

As expected, the __import__ gets the old version of the module which doesn't have the methods I just added at runtime.

Is it possible to make the __import__ calls import the newer version of the class (which includes the methods I added)?

Please note that I prefer keeping the automation system untouched (even when it would help solving the problem faster).

Thanks

Tal.

+1  A: 
reload(testmodule)

might work.

Ivo van der Wijk
+2  A: 

You need to be aware that reloading a module won't magically replace old instances. Even if you do reload, only new objects will use the new code!

The only way to replace code during runtime is to wrap everything in a proxy object! You can sometimes do this, ie for specific, self-contained modules, but in most cases it's simply not a reasonable approach.

Quick demonstration:

>>> import asd
>>> asd.s
'old'
>>> t = asd.s
>>> reload(asd) # I edited asd.py before
<module 'asd' from 'asd.py'>
>>> asd.s # new module content
'new'
>>> t # but this is still old!
'old'

Most applications that looks like it reloads code actually just restart!

THC4k
This sort of behavior is why you need to hijack the reloading mechanism early. In a testing scenario, you would do it before you start creating the fixtures. And you would _never_ do it in a real program. right?
aaronasterling
The problem is that there is no way to prevent `t = asd.s` and anyone might do that (ie. just for the stupid reason of saving one attribute lookup). Trying to `reload` will then give you a mix of old and new code and that will definitely not make debugging easier ...
THC4k
correct. My previous comment was off the mark. That being said, any calls _after_ the module is reloaded will have the new attributes. As long as all new attributes are in place by the time the fixtures are getting set up, this shouldn't be a problem for testing.
aaronasterling