[Python-Dev] unexpected import behaviour

Daniel Waterworth da.waterworth at gmail.com
Fri Jul 30 08:26:26 CEST 2010


On 29 July 2010 07:32, 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?
>
> Thanks,
>
> Daniel
>
> --
> active-thought.com
>

@Oleg: I know this list is plagued by people who should be on
comp.lang.python, but I assure you I'm not looking to learn to program
in python, in fact I've been programming competently in python for
many years. This is purely CPython bug-fixing/the discussion of
implementation choices.

@ Nick: In terms of backward compatibility, it would only break
someone's code if they were relying on having the same module imported
twice as different instances. Could this behaviour be added to
python3.2? I'm not sure how far you are through the release cycle. Or
even just a warning as Michael suggested?

@Michael: Yes, I guessed as much. In fact adding,

import sys, os

if globals().get("__file__") and __name__=='__main__':
    base = os.path.basename(__file__)
    ext = base.rfind('.')
    if ext > 0:
        main_name = base[:ext]
    else:
        main_name = base
    sys.modules[main_name] = __import__('__main__')

to the beginning of a file solves the problem, but seems more than a
little hacky and I think I've missed edge cases with packages.

Thanks for your answers,

Daniel

-- 
active-thought.com


More information about the Python-Dev mailing list