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 test_1():
     import test
     print Test == test.Test

if __name__ == '__main__':
     test_1()

and then run it ($ python test.py), it'll print False. Now try:

$python
import test
test.test_1()

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.


_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to