What ought to persist after a program is run?

Donn Cave donn at u.washington.edu
Wed Jun 16 21:22:41 CEST 2004


In article <b4a8ffb6.0406161049.355089c9 at posting.google.com>,
 tkpmep at hotmail.com (Thomas Philips) wrote:

> Here's a very simple program with an odd twist:
> class Player(object):
>     def __init__(self,name):
>         self.name = name
> 
> hero = Player("A")
> print "hero",hero
> 
> If I run it in IDLE and then type dir() at the prompt, I get
> >>>['Player', '__builtins__', '__doc__', '__name__', 'hero']
> 
> However, if I modify the program as follows
> class Player(object):
>     def __init__(self,name):
>         self.name = name
> def main():
>     hero = Player("A")
>     print "hero=",hero
> main()
> 
> and then run it in IDLE and type dir at the prompt, I get
> >>>['Player', '__builtins__', '__doc__', '__name__']
> 
> Why does 'hero' not appear in the workspace directory when main() is
> invoked and vice versa?

Because main(), like any function, binds the object to its
local namespace, not the "global" (module) namespace.

Each function has its own, separate namespace, every time
it's invoked.  Ordinarily, the module namespace is mostly
populated with functions, classes etc. defined in the
module source (or typed in at the keyboard in your case.)
Functions use their own namespaces for scratch space,
and "return" the results of their computation, or modify
input parameters.  This isolation simplifies interdependencies
between functions, so they're easier to manage as code gets
rewritten.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list