[Python-Dev] unexpected import behaviour

Nick Coghlan ncoghlan at gmail.com
Thu Jul 29 14:56:21 CEST 2010


On Thu, Jul 29, 2010 at 4:32 PM, Daniel Waterworth
<da.waterworth at gmail.com> 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,
>
> 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?

The behaviour is expected, but there's no particularly deep rationale
for it - the interpreter just doesn't go out of its way to try and
figure out what __main__ *would* have been called if it had been
imported rather than executed (your script will still print False even
if you run it via "python -m test").

We certainly *could* put __main__ into sys.modules under both names
(i.e. "__main__" and "test" in your example), but the backwards
compatibility implications of doing so aren't particularly clear.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list