Re: Weird Python behavior Monty Zukowski (mzukowski@bco.com)
Wed, 26 Apr 2000 15:49:01 -0700

Boy that is weird. Here's what is happening:

main is "running" as the invoked module for Python. it first imports broken, which imports main. Import causes the code in the module to run, but apparently the runtime doesn't recognize that main is already in the process of being imported. It is imported again, as you can see if you put an "else" in for your name=="__main__" test. 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...cross posting to comp.lang.python might let other experts shed a little more light on it.

A simple workaround would be to make your if name =="__main__": block into a function called run, and then make yet another python module called runner.py which did this:

import main
main.run()

Monty

> -----Original Message-----
> From: Jonathan S. Shapiro [mailto:shap@eros-os.org]
> Sent: Wednesday, April 26, 2000 12:05 PM
> To: DCMS List
> Subject: Weird Python behavior
>
>
> I have a stupid python question. I'm hoping somebody can
> answer it. I'm not
> clear
> on whether it's a failure of my understanding or a bug in
> Python or both.
> The problem involves failed visibility of updates to global
> variables. I
> have narrowed it down to a small example. I am running
> python 1.5.2. I'm
> getting desperate, because I'm stuck until this is solved.
>
> I have two python files
>
> main.py:
> ===
>
> import broken;
>
> somevar = None;
>
> if __name__ == "__main__":
> global somevar
>
> somevar = 1;
> broken.showme();
> ===
>
> broken.py:
> ===
> import main
>
> def showme():
> print main.somevar
> ===
>
> My question: Showme() prints "None". Why doesn't showme()
> print the value
> "1"?
>
> What's going on here?
>
>
>