Re: Weird Python behavior Ka-Ping Yee (ping@lfw.org)
Thu, 27 Apr 2000 01:54:37 -0700 (PDT)

On Wed, 26 Apr 2000, Monty Zukowski wrote:
> So broken is referencing a module main which is not the
> same module as the one that is running the program. I can't
> comment on whether this is a bug or a feature...

It's not really a bug. It's part of the intended design: running a script is not the same as importing a module.

When you run a script, it always runs in a namespace called "__main__". So running main.py puts it in "__main__"; when broken.py attempts to import "main", it then loads main.py as the module "main".

main.py explicitly sets somevar to 1 only in the namespace called "__main__", yet broken.py is asking for the namespace called "main", so it's not going to get the same one.

Whether the design intent is sound is another argument, but there are some points in its favour -- for example, the running script doesn't need to have a filename, and we want to guarantee that "python < main.py" will behave the same as "python main.py". Also think about what happens when main.py is executable and has a #!/usr/bin/env python at the top. You want it to behave the same way in all three cases, and it may not always have a filename.

> > main.py:
> > ===
> >
> > import broken;
> >
> > somevar = None;
> >
> > if __name__ == "__main__":
> > global somevar
> >
> > somevar = 1;
> > broken.showme();
> > ===
> >
> > broken.py:
> > ===
> > import main
> >
> > def showme():
> > print main.somevar
> > ===

"To be human is to continually change. Your desire to remain as you are is what ultimately limits you."