Skunkwaffle
Skunkwaffle

Reputation: 624

Reloading module causes different results

During testing I added a reload command to my test cases so I could change code in several different places without having to reload everything manually and I noticed the reloads seemed to affect the results of the tests.

Here's what I did:

import mymodule
import mymodule.rules as rules

def testcase():
    reload(mymodule)
    reload(rules)

    # The rest of the test case

Everything works fine like this, or when both reloads are commented out, but when I comment out the second reload the results of the test are different. Is there something that happens during the reload process that I'm not aware of that necessitates reloading all scripts from a module once the module is reloaded? Is there some other explanation?

I'm not sure if this is relevant, but rules is a separate script inside the package that includes this line:

from mymodule import Rule

Upvotes: 1

Views: 71

Answers (2)

Sam Mussmann
Sam Mussmann

Reputation: 5993

I'm not sure exactly what is causing your problem, but I think you may be misusing reload().

According to the docs, reload() will

Reload a previously imported module.

However, if you're running this in a testcase, there won't be any changes to the module between when you import it and when you reload it, right? In order for there to be changes, I think you would have to be changing those files as the test case runs, which is probably not a good idea.

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 602625

The information in your question is rather vague, and your terminology rather non-standard. From

rules is a separate script inside mymodule.

I infer that mymodule is actually a package, and it seems it does not automatically import rules upon import. This implies that after executing

import mymodule

there will be no mymodule.rules, but after executing

import mymodule.rules as rules

the module rules will be imported into the namespace of mymodule. (Side note: The latter code line is usually written as from mymodule import rules.)

After executing the first reload() statement, you will get a frsh copy of mymodule, which wil not contain mymodule.rules – this will only be recreated after the second reload() statement.

I had to do a lot of guessing for this answer, so I might have gotten it wrong. The reload() statement has lots of subtleties, as can be seen in its documentation, so its better to only use it if you are closely familiar with Python's import machinery.

(Another side note: If rule.py resides inside the package mymodule, as your setup seems to be, you should use a relative import there. Instead of

from mymodule import Rule

you should do

from . import Rule

I also recommend from __future__ import absolute_import for more transparent import rules.)

Upvotes: 2

Related Questions