DekGenius.com
[ Team LiB ] Previous Section Next Section

27.1 Exploring on Your Own

Before digging into specific tasks, we should say a brief word about self-exploration. We have not been exhaustive in coverage of object attributes or module contents in order to focus on the most important aspects of the objects under discussion. If you're curious about what we've left out, you can look it up in the Library Reference, or you can poke around in the Python interactive interpreter, as shown in this section.

The dir built-in function returns a list of all of the attributes of an object, and, along with the type built-in, provides a great way to learn about the objects you're manipulating. For example:

>>> dir([  ])                             # What are the attributes of lists?
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', 
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

What this tells you is that the empty list object has a few methods: append, count, extend, index, insert, pop, remove, reverse, sort, and a lot of "special methods" that start with an underscore (_) or two (__). These are used under the hood by Python when performing operations like +. Since these special methods are not needed very often, we'll write a simple utility function that will not display them:

>>> def mydir(obj):
...     orig_dir = dir(obj)
...     return [item for item in orig_dir if not item.startswith('_')]
...     
>>>

Using this new function on the same empty list yields:

>>> mydir([  ])                             # What are the attributes of lists?
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

You can then explore any Python object:

>>> mydir((  ))                                # What are the attributes of tuples?
[  ]                                        # Note: no "normal" attributes
>>> import sys                            # What are the attributes of files?
>>> mydir(sys.stdin)                      # What are the attributes of files?
['close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 'read', 'readinto', 
'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write',
 'writelines', 'xreadlines']
 >>> mydir(sys)                           # Modules are objects too.
['argv', 'builtin_module_names', 'byteorder', 'copyright', 'displayhook', 
'dllhandle', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable',
'exit', 'getdefaultencoding', 'getrecursionlimit', 'getrefcount', 'hexversion',
'last_traceback', 'last_type', 'last_value', 'maxint', 'maxunicode', 'modules',
'path', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 
'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 
'version_info', 'warnoptions', 'winver'] 
>>> type(sys.version)                    # What kind of thing is 'version'?
<type 'string'>
>>> print repr(sys.version)              # What is the value of this string?
'2.3a1 (#38, Dec 31 2002, 17:53:59) [MSC v.1200 32 bit (Intel)]'

Recent versions of Python also contain a built-in that is very helpul to beginners, named (appropriately enough) help:

>>> help(sys)
Help on built-in module sys:
NAME
    sys

FILE
     (built-in)

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the 
    interpreter.

    Dynamic objects:

    argv--command line arguments; argv[0] is the script pathname if known
    path--module search path; path[0] is the script directory, else ''
    modules--dictionary of loaded modules

    displayhook--called to show results in an interactive session
    excepthook--called to handle any uncaught exception other than 
    SystemExit

    To customize printing in an interactive session or to install a 
    custom top-level exception handler, assign other functions to replace
    these.
    ...

There is quite a lot to the online help system. We recommend that you start it first in its "modal" state, just by typing help( ). From then on, any string you type will yield its documentation. Type quit to leave the help mode.

>>> help(  )
Welcome to Python 2.2! This is the online help utility
...
help> socket
Help on module socket:

NAME
    socket

FILE
    c:\python22\lib\socket.py

DESCRIPTION
    This module provides socket operations and some related functions.
    On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
    On other systems, it only supports IP. Functions specific for a
    socket are available as methods of the socket object.

    Functions:

    socket(  ) -- create a new socket object
    fromfd(  ) -- create a socket object from an open file descriptor [*]
    gethostname(  ) -- return the current hostname
    gethostbyname(  ) -- map a hostname to its IP number
    gethostbyaddr(  ) -- map an IP number or hostname to DNS info
    getservbyname(  ) -- map a service name and a protocol name to a port 
        ...
help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

and                 elif                global              or
assert              else                if                  pass
break               except              import              print
class               exec                in                  raise
continue            finally             is                  return
def                 for                 lambda              try
del                 from                not                 while
help> topics

Here is a list of available topics.  Enter any topic name to get more help.

ASSERTION           DEBUGGING           LITERALS         SEQUENCEMETHODS1
ASSIGNMENT          DELETION            LOOPING          SEQUENCEMETHODS2
ATTRIBUTEMETHODS    DICTIONARIES        MAPPINGMETHODS   SEQUENCES
ATTRIBUTES          DICTIONARYLITERALS  MAPPINGS         SHIFTING
AUGMENTEDASSIGNMENT ELLIPSIS            METHODS          SLICINGS
BACKQUOTES          EXCEPTIONS          MODULES          SPECIALATTRIBUTES
BASICMETHODS        EXECUTION           NAMESPACES       SPECIALIDENTIFIERS
BINARY              EXPRESSIONS         NONE             SPECIALMETHODS
BITWISE             FILES               NUMBERMETHODS    STRINGMETHODS
BOOLEAN             FLOAT               NUMBERS          STRINGS
CALLABLEMETHODS     FORMATTING          OBJECTS          SUBSCRIPTS
CALLS               FRAMEOBJECTS        OPERATORS        TRACEBACKS
CLASSES             FRAMES              PACKAGES         TRUTHVALUE
CODEOBJECTS         FUNCTIONS           POWER            TUPLELITERALS
COERCIONS           IDENTIFIERS         PRECEDENCE       TUPLES
COMPARISON          IMPORTING           PRINTING         TYPEOBJECTS
COMPLEX             INTEGER             PRIVATENAMES     TYPES
CONDITIONAL         LISTLITERALS        RETURNING        UNARY
CONVERSIONS         LISTS               SCOPING          UNICODE
help> TYPES
  3.2 The standard type hierarchy

  Below is a list of the types that are built into Python. Extension
  modules written in C can define additional types. Future versions of
  Python may add types to the type hierarchy (e.g., rational numbers,
  efficiently stored arrays of integers, etc.).
  ...

help> quit
>>>
    [ Team LiB ] Previous Section Next Section