Python questions from C/Perl/Java programmer

Will Ware wware at world.std.com
Mon Jul 24 22:10:00 EDT 2000


ye, wei (yw at alabanza.net) wrote:
> I can bear the {} issue, however I couldn't bear with variable without
> declaration.
> I wrote many applications, I couldn't live without declaration. For big
> project,
> there are so many scripts, everyone may be misspell variable name.
> It's very timeconsume and hard to find out such problem, which should
> be easy checked out by compiler.

You would think this would be a problem, but it turns out not to
be bad. Python has a good scheme for keeping things clean, called
namespaces. Namespaces make sure that each global variable is
associated with a particular module. I'll often begin a script with
a line importing several modules, like this:

import os, sys, string, re, urllib

To use the variables and functions within any one of these, I need
to call it out as a member of that module, like this:

arg1 = sys.argv[1]
arg2 = sys.argv[2]
while myOwnString[0] in string.lowercase:
	do something...
os.system('rm -f files to be deleted')

and so forth. The module name appears as a prefix. Java uses a similar
scheme for the same purpose.

If two modules have identically named variables or functions, I can tell
them apart just by looking at the prefix.

If I misspell the name of a function or variable, I get a NameError
(meaning that Python does not recognize the name I used) and I know I
need to check it.

You lose all the benefits of separate namespaces if you import this
way:

from os import *
from sys import *
...etc...

because all those names now appear together in the global namespace,
and if two modules have the same name for two different things, one will
get lost. The 'from <module> import <stuff>' can be convenient when you're
in a hurry, as it saves typing, but it's a bad habit, and if the
script is useful long-term, you'll want to change all those names
anyway. So don't get too addicted to the from...import form.
-- 
 - - - - - - - - - - - - - - - - - - - - - - - -
Resistance is futile. Capacitance is efficacious.
Will Ware	email:    wware @ world.std.com



More information about the Python-list mailing list