On 1/30/16 5:47 PM, Steven D'Aprano 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.
Something like this does happen in the real world. A class is defined in the main module, and then the module is later imported with its real name. Now you have __main__.Class and module.Class both defined. You don't need to actually "import __main__" for it to happen. __main__.Class is used implicitly from the main module simply as Class. --Ned.