[Tutor] command line

Lloyd Kvam pythontutor@venix.com
Sat, 30 Mar 2002 18:24:52 -0500


I'll take a stab at answering this.
(Dman, thanks for the -i tip.  Yet another useful tidbit learned
from this list.)

 >>> print __name__
__main__
 >>> import DB		# DB contains line print __name__
DB

The python interpreter provides a namespace called __main__.  Each imported
module (file) has a namespace named for the module.  When a module (file) is
run directly it is using the __main__ namespace.  With the -i argument,
the interpreter will continue operating, hooking itself to the keyboard
and monitor for interactive use.

Only names in the builtin name space can be accessed from anywhere without
qualifiers.  To access something in DB, I must use "DB.something".  In C,
functions and extern variables are truly global, accessible anywhere
without qualifiers.  In Python a name is accessible without qualifiers
only if it is local, in the module, or in builtins.  The globals
keyword sounded to me like it could cross module boundaries.  It doesn't.

Namespace names generally seem to be interpreted relative to __main__.  I
have a module DB.py with some useful database functions.  Other modules
a and b can import DB.  If module a causes DB.x to bind to a value of 3,
I can use module b to print DB.x and see that value.  Using the syntax,
	from <module> import *
muddles how namespaces work.  Wesley Chun's book has an example of this
muddling on page 391.

I do not yet have a solid handle on how namespaces, files and packages
interact.

Erik Price wrote:

> 
> On Saturday, March 30, 2002, at 03:07  PM, dman wrote:
> 
>> You can also do
>>     python -i <filename>
>> to drop into an interactive shell after executing the file.  You'll
>> have the same namespace as the file's module too.
> 
> 
> Can I ask an unrelated question?  What does that mean -- "you'll have 
> the same namespace as the file's module too".
> 
> I understand the difference between local/global/builtin namespaces (I 
> think): the local namespace is for names specific to the current context 
> (a function or class or module, for instance), the global namespace is 
> for names available to all contexts, and the builtin namespace is for 
> names that are predefined by Python and often start with two underscores.
> 
> I'm guessing that the quote above means that the names available to the 
> script are now available to the user in the shell, when the shell is 
> invoked in this fashion, such that if the script imported from module 
> "Stock", all of the names in "Stock" are available and don't need to be 
> imported.  But if someone could confirm this it would help me grasp the 
> concept of namespaces better.
> 
> Thanks,
> Erik
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582