[Python-Dev] unexpected import behaviour (original) (raw)
Michael Foord fuzzyman at voidspace.org.uk
Thu Jul 29 15:05:37 CEST 2010
- Previous message: [Python-Dev] unexpected import behaviour
- Next message: [Python-Dev] unexpected import behaviour
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 29/07/2010 07:32, Daniel Waterworth wrote:
Hi,
I'm not sure if this is a bug or not, I certainly didn't expect it. If you create a file called test.py with the following contents,
The issue is that when your code is executed as a script it is run as the main module and not as the test module. When you import test you then import the same module with a different name - and your Test class is recreated (so main.Test is then different from test.Test). When you import your code as test and it then reimports itself it is only created once.
This is expected behaviour (not a bug), but it frequently confuses even relatively experienced programmers (it can happen by accident and cause hard to track down bugs) and I personally think that Python would be improved by issuing a warning if a main script reimports itself.
All the best,
Michael Foord
class Test: pass
def test1(): import test print Test == test.Test if name == 'main': test1() and then run it ($ python test.py), it'll print False. Now try: $python import test test.test1() and it'll print True. Is this behaviour expected? What was the rationale for it if is? Thanks, Daniel
-- http://www.ironpythoninaction.com/ http://www.voidspace.org.uk/blog
READ CAREFULLY. By accepting and reading this email you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies (”BOGUS AGREEMENTS”) that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer.
- Previous message: [Python-Dev] unexpected import behaviour
- Next message: [Python-Dev] unexpected import behaviour
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]