[Python-ideas] Prevent importing yourself?

Nathaniel Smith njs at pobox.com
Sat Jan 30 18:25:44 EST 2016


On Sat, Jan 30, 2016 at 2:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Jan 30, 2016 at 06:19:35AM -0500, Ned Batchelder wrote:
>
>> While we're at it though, re-importing __main__ is a separate kind of
>> behavior that is often a problem, since it means you'll have the same
>> classes defined twice.
>
> As far as I can tell, importing __main__ is fine. It's only when you
> import __main__ AND the main module under its real name at the same time
> that you can run into problems -- and even then, not always. The sort of
> errors I've seen involve something like this:
>
> import myscript
> import __main__  # this is actually myscript
> a = myscript.TheClass()
> # later
> assert isinstance(a, __main__.TheClass)
>
> which fails, because myscript and __main__ don't share state, despite
> actually coming from the same source file.
>
> So I think it's pretty rare for something like this to actually happen.
> I've never seen it happen by accident, I've only seen it done
> deliberately as a counter-example to to the "modules are singletons"
> rule.

Not only is importing __main__ fine, it's actually unavoidable...
__main__ is just an alias to the main script's namespace.

-- test_main.py --
class Foo:
    pass
import __main__
# Prints "True"
print(Foo is __main__.Foo)
-- end test_main.py --

So importing __main__ never creates any new copies of any singletons;
it's only importing the main script under its filesystem name that
creates the problem.

-n

-- 
Nathaniel J. Smith -- https://vorpus.org


More information about the Python-ideas mailing list