Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


WDVL Newsletter

Active Server Pages
JSP/Java Servlets
Microsoft SQL Server
Daily Backup
Dedicated Servers
Streaming Audio/Video
24-hour Support    

jobs.webdeveloper.com

Hiermenus


e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


The Built-In Namespace - Page 8

May 24, 2001

>>> import scopetest
>>> z = 2
>>> scopetest. f( z)
global: ['v', '__ doc__ ', 'f', '__ file__ ', '__ name__ ',
'__ builtins__ ']
entry local: {'x': 2}
exit local: {'w': 6, 'x': 2, 'y': 2}

The global namespace is now that of the scopetest module and includes the function f and integer v (but not z from our interactive session). Thus, when creating a module you have complete control of the namespaces of its functions.

We've now covered local and global namespaces. Next, let's move on to the built-in namespace. We'll introduce another built-in function, dir, which, given a module, returns a list of the names defined in it.

>>> dir(__ builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'EOFError',
'Ellipsis', 'EnvironmentError', 'Exception',
'FloatingPointError', 'IOError', 'ImportError', 'IndexError',
'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError',
'NameError', 'None', 'NotImplementedError', 'OSError',
'OverflowError', 'RuntimeError', 'StandardError',
'SyntaxError', 'SystemError', 'SystemExit', 'TypeError',
'ValueError', 'ZeroDivisionError', '_ ', '__ debug__ ', '__ doc__ ',
'__ import__ ', '__ name__ ', 'abs', 'apply', 'callable', 'chr',
'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dir',
'divmod', 'eval', 'execfile', 'exit', 'filter', 'float',
'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'input',
'int', 'intern', 'isinstance', 'issubclass', 'len', 'list',
'locals', 'long', 'map', 'max', 'min', 'oct', 'open', 'ord',
'pow', 'quit', 'range', 'raw_ input', 'reduce', 'reload', 'repr',
'round', 'setattr', 'slice', 'str', 'tuple', 'type', 'vars',
'xrange']

There are a lot of entries here. Those ending in Error and System Exit are the names of the exceptions built-in to Python. These will be discussed in "Exceptions" (chapter 14).

The last group (from abs to xrange), are built-in functions of Python. We have already seen many of these in this book and will see more. However, they won't all be covered here. When interested, you can find details on the rest in the Python Library Reference. You can also at any time easily obtain the documentation string for any of them:

>>> print max.__ doc__
max( sequence) -> value
max( a, b, c, ...) -> value

With a single sequence argument, return its largest item.
With two or more arguments, return the largest argument.
>>>

As mentioned earlier, it is not unheard of for a new Python programmer to inadvertently override a built-in function.

>>> list(" Peyto Lake")
['P', 'e', 'y', 't', 'o', ' ', 'L', 'a', 'k', 'e']
>>> list = [1, 3,5, 7]
>>> list(" Peyto Lake")
Traceback (innermost last):
File "< stdin>", line 1, in ?
TypeError: call of non-function (type list)

The Python interpreter will not look beyond our new binding for list as a list, even though we are using function syntax.

The same thing will of course happen if we try to use the same identifier twice in a single namespace. The previous value will be overwritten, regardless of its type:

>>> import string
>>> string = "Mount Rundle"
>>> string. split(" Bow Lake")
Traceback (innermost last):
  File "< stdin>", line 1, in ?
AttributeError: 'string' object has no attribute 'split'

Once aware of this, it isn't a significant issue. Reusing identifiers, even for different types of objects, wouldn't make for the most readable code anyway. If we do inadvertently make one of these mistakes when in interactive mode, it's easy to recover. We can use del to remove our binding, to regain access to an overridden built-in, or import our module again, to regain access.

>>> del list
>>> list(" Peyto Lake")
['P', 'e', 'y', 't', 'o', ' ', 'L', 'a', 'k', 'e']
>>> import string
>>> string. split(" Bow Lake")
['Bow', 'Lake']

The locals and globals functions can be quite useful as simple debugging tools. The dir function doesn't give the current settings but if called without parameters, it returns a sorted list of the identifiers in the local namespace. This will help catch the mistyped variable error that compilers may usually catch for you in languages that require declarations:

>>> x1 = 6
>>> xl = x1 -2
>>> x1
6
>>> dir()
['__ builtins__ ', '__ doc__ ', '__ name__ ', 'x1', 'xl']

The debugger that is bundled with IDLE has settings where you can view the local and global variable settings as you step through your code, and what it displays is the output of the locals and globals functions.

Creating Bindings - Page 7
The Quick Python Book
Opening Files and File Objects - Page 9


Up to => Home / Authoring / Languages / Python / Quick




Jupiter Online Media: internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and Jupiter Online Media

Jupitermedia Corporate Info


Legal Notices, Licensing, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers