Name space quirk?
Tim Roberts
timr at probo.com
Wed Jul 25 01:39:15 EDT 2001
n_d_gangadhar at yahoo.com (NANDYALA D Gangadhar) wrote:
>
>I understand what you said. So I have:
>
>1. Before one uses a name in __main__, one has to make sure that it is
> not used anywhere in the Module, even without the qualifier "global";
> failure to do so could be unpleasent.
If I may be so bold as to break in, I think you are missing the main point.
In my view, the key concept to grasp is that Python namespaces are dynamic,
not static. A variable is added to a namespace when a statement assigning
it a value is executed, and a variable does not need to exist until a
statement that needs it is executed. Here's an example:
import os
def abc():
return myValue
print abc()
myValue = 1
print abc()
The fact that myValue does not exist at the time abc() is defined is
irrelevant. It won't even be looked for until abc() is actually invoked.
The first time abc() is called, myValue has not been defined, so it will
generate an exception. However, the SECOND call to abc() would succeed (if
the first one had not already failed), because by the time it executes,
"myValue" has been added to the global namespace.
This is quite different from languages like Pascal and C.
>2. OTOH, __main__ namespace is not searched by the module if it is
> imported, since it is only __builtins__ that is searched, after
> the module's name space.
No. Rather, when a module is imported, __name__ is not equal to
"__main__", so the section starting with:
if __name__ == '__main__':
does not get executed. Thus, none of the changes it might have made to the
global namespace will happen.
>Hence, I get NameError with
>
>nspace1.py:
>
>#!/usr/bin/env python
>
>from nspace import *
>
>if __name__ == '__main__':
> f = sys.argv[0] + ".out"
> myfile = open (f, 'w')
> hello (myfile)
>
>[myfile was declared global in nspace.py] in interactive mode as well.
If "myfile" is assigned only in the "if __name__ == '__main__':" section,
then it will not exist, because that section will not be executed. On the
other hand, if nspace.py looked like this:
myfile = 'xyz'
if __name__ == '__main__':
myfile = 'abc'
then your nspace1.py example would work. The statement "myfile = 'xyz'"
would be executed when you did the import, and would then be imported into
nspace1.py's global namespace.
I hope this helps to explain why the behavior IS consistent.
--
- Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-list
mailing list