Python in a Nutshell

Book description

Ask any Python aficionado and you'll hear that Python programmers have it all: an elegant language that offers object-oriented programming support, a readable, maintainable syntax, integration with C components, and an enormous collection of precoded standard library and extension modules. Moreover, Python is easy to learn but powerful enough to take on the most ambitious programming challenges. But what Python programmers have lacked is one concise and clear reference resource, with the appropriate measure of guidance in how best to use Python's great power. Now Python in a Nutshell fills this need. In the tradition of O'Reilly's "In a Nutshell" series, this book offers Python programmers one place to look when they need help remembering or deciphering the syntax of this open source language and its many modules. This comprehensive reference guide makes it easy to look up all the most frequently needed information--not just about the Python language itself, but also the most frequently used parts of the standard library and the most important third-party extensions. Python in a Nutshell focuses on Python 2.2 (and all its point releases), currently the most stable and widespread Python release. This book includes:

  • A fast-paced tutorial on the syntax of the Python language itself

  • An explanation of object-oriented programming in Python, covering both the classic and new-style object models

  • Coverage of other core topics, including exceptions, modules, strings, and regular expressions

  • A quick reference for Python's built-in types and functions, as well as the key modules in the Python standard library, including sys, os, time, thread, math, and socket, among many others

  • Reference material on important third-party extensions, such as Numeric and Tkinter

  • Information about extending Python and embedding it into other applications

Python in a Nutshell provides a solid, no-nonsense quick reference to information that programmers rely on the most. This latest addition to the best-selling "In a Nutshell" series will immediately earn its place in any Python programmer's library.

Table of contents

  1. Python in a Nutshell
    1. Preface
      1. How This Book Is Organized
      2. Conventions Used in This Book
        1. Reference Conventions
        2. Typographic Conventions
      3. How to Contact Us
      4. Acknowledgments
    2. I. Getting Started with Python
      1. 1. Introduction to Python
        1. The Python Language
        2. The Python Standard Library and Extension Modules
        3. Python Implementations
          1. CPython
          2. Jython
          3. Choosing Between CPython and Jython
          4. Python .NET
          5. Licensing and Price Issues
        4. Python Development and Versions
        5. Python Resources
          1. Documentation
          2. Newsgroups and Mailing Lists
          3. Special Interest Groups
          4. Python Business Forum
          5. Python Journal
          6. Extension Modules and Python Sources
          7. The Python Cookbook
          8. Books and Magazines
      2. 2. Installation
        1. Installing Python from Source Code
          1. Windows
            1. Uncompressing and unpacking the Python source code
            2. Building the Python source code with Microsoft Visual C++
            3. Building Python for debugging
            4. Installing after the build
            5. Building Python for Cygwin
          2. Unix-like Platforms
            1. Uncompressing and unpacking the Python source code
            2. Configuring, building, and testing
            3. Installing after the build
          3. Apple Macintosh
        2. Installing Python from Binaries
        3. Installing Jython
      3. 3. The Python Interpreter
        1. The python Program
          1. Environment Variables
          2. Command-Line Syntax and Options
          3. Interactive Sessions
        2. Python Development Environments
          1. IDLE
          2. Other Free Cross-Platform Python IDEs
          3. Platform-Specific Free Python IDEs
          4. Commercial Python IDEs
          5. Free Text Editors with Python Support
        3. Running Python Programs
        4. The Jython Interpreter
    3. II. Core Python Language and Built-ins
      1. 4. The Python Language
        1. Lexical Structure
          1. Lines and Indentation
          2. Tokens
            1. Identifiers
            2. Keywords
            3. Operators
            4. Delimiters
            5. Literals
          3. Statements
            1. Simple statements
            2. Compound statements
        2. Data Types
          1. Numbers
          2. Sequences
            1. Strings
            2. Tuples
            3. Lists
          3. Dictionaries
          4. None
          5. Callables
          6. Boolean Values
        3. Variables and Other References
          1. Variables
            1. Object attributes and items
            2. Accessing nonexistent references
          2. Assignment Statements
            1. Plain assignment
            2. Augmented assignment
          3. del Statements
        4. Expressions and Operators
        5. Numeric Operations
          1. Coercion and Conversions
          2. Arithmetic Operations
          3. Comparisons
          4. Bitwise Operations on Integers
        6. Sequence Operations
          1. Sequences in General
            1. Coercion and conversions
            2. Concatenation
            3. Sequence membership
            4. Indexing a sequence
            5. Slicing a sequence
          2. Strings
          3. Tuples
          4. Lists
            1. Modifying a list
            2. In-place operations on a list
            3. List methods
        7. Dictionary Operations
          1. Dictionary Membership
          2. Indexing a Dictionary
          3. Dictionary Methods
        8. The print Statement
        9. Control Flow Statements
          1. The if Statement
          2. The while Statement
          3. The for Statement
            1. Iterators
            2. range and xrange
            3. List comprehensions
          4. The break Statement
          5. The continue Statement
          6. The else Clause on Loop Statements
          7. The pass Statement
          8. The try Statement
        10. Functions
          1. The def Statement
          2. Parameters
          3. Attributes of Function Objects
          4. The return Statement
          5. Calling Functions
            1. The semantics of argument passing
            2. Kinds of arguments
          6. Namespaces
            1. The global statement
            2. Nested functions and nested scopes
          7. lambda Expressions
          8. Generators
          9. Recursion
      2. 5. Object-Oriented Python
        1. Classic Classes and Instances
          1. The class Statement
          2. The Class Body
            1. Attributes of class objects
            2. Function definitions in a class body
            3. Class-private variables
            4. Class documentation strings
          3. Instances
            1. __init__
            2. Attributes of instance objects
            3. The factory-function idiom
          4. Attribute Reference Basics
          5. Bound and Unbound Methods
            1. Unbound method details
            2. Bound method details
          6. Inheritance
            1. Overriding attributes
            2. Delegating to superclass methods
            3. “Deleting” class attributes
        2. New-Style Classes and Instances
          1. The Built-in object Type
          2. Class-Level Methods
            1. Static methods
            2. Class methods
          3. New-Style Classes
            1. __init__
            2. __new__
          4. New-Style Instances
            1. Properties
            2. __slots__
            3. __getattribute__
            4. Per-instance methods
          5. Inheritance in the New-Style Object Model
            1. Method resolution order
            2. Cooperative superclass method calling
        3. Special Methods
          1. General-Purpose Special Methods
            1. __call__
            2. __cmp__
            3. __del__
            4. __delattr__
            5. __eq__, __ge__, __gt__, __le__, __lt__, __ne__
            6. __getattr__
            7. __getattribute__
            8. __hash__
            9. __init__
            10. __new__
            11. __nonzero__
            12. __repr__
            13. __setattr__
            14. __str__
            15. __unicode__
          2. Special Methods for Containers
            1. Sequences
            2. Mappings
            3. Sets
            4. Container slicing
            5. Container methods
              1. __contains__
              2. __delitem__
              3. __getitem__
              4. __iter__
              5. __len__
              6. __setitem__
          3. Special Methods for Numeric Objects
            1. __abs__, __invert__, __neg__, __pos__
            2. __add__, __div__, __floordiv__, __mod__, __mul__, __sub__,__truediv__
            3. __and__, __lshift__, __or__, __rshift__, __xor__
            4. __coerce__
            5. __complex__, __float__, __int__, __long__
            6. __divmod__
            7. __hex__, __oct__
            8. __iadd__, __idiv__, __ifloordiv__, __imod__, __imul__, __isub__, __itruediv__
            9. __iand__, __ilshift__, __ior__, __irshift__, __ixor__
            10. __ipow__
            11. __pow__
            12. __radd__, __rdiv__, __rmod__, __rmul__, __rsub__
            13. __rand__, __rlshift__, __ror__, __rrshift__, __rxor__
            14. __rdivmod__
            15. __rpow__
        4. Metaclasses
          1. How Python Determines a Class’s Metaclass
          2. How a Metaclass Creates a Class
            1. Defining and using your own metaclasses
            2. A substantial custom metaclass example
      3. 6. Exceptions
        1. The try Statement
          1. try/except
          2. try/finally
        2. Exception Propagation
        3. The raise Statement
        4. Exception Objects
          1. The Hierarchy of Standard Exceptions
          2. Standard Exception Classes
        5. Custom Exception Classes
        6. Error-Checking Strategies
          1. Handling Errors in Large Programs
          2. Logging Errors
          3. The assert Statement
          4. The __debug__ Built-in Variable
      4. 7. Modules
        1. Module Objects
          1. The import Statement
            1. Module body
            2. Attributes of module objects
            3. Python built-ins
            4. Module documentation strings
            5. Module-private variables
          2. The from Statement
        2. Module Loading
          1. Built-in Modules
          2. Searching the Filesystem for a Module
          3. The Main Program
          4. The reload Function
          5. Circular Imports
          6. sys.modules Entries
          7. Custom Importers
        3. Packages
        4. The Distribution Utilities (distutils)
      5. 8. Core Built-ins
        1. Built-in Types
          1. classmethod
          2. complex
          3. dict
          4. file, open
          5. float
          6. int
          7. list
          8. long
          9. object
          10. property
          11. staticmethod
          12. str
          13. super
          14. tuple
          15. type
          16. unicode
        2. Built-in Functions
          1. __import__
          2. abs
          3. apply
          4. bool
          5. buffer
          6. callable
          7. chr
          8. cmp
          9. coerce
          10. compile
          11. delattr
          12. dir
          13. divmod
          14. eval
          15. execfile
          16. filter
          17. getattr
          18. globals
          19. hasattr
          20. hash
          21. hex
          22. id
          23. input
          24. intern
          25. isinstance
          26. issubclass
          27. iter
          28. len
          29. locals
          30. map
          31. max
          32. min
          33. oct
          34. ord
          35. pow
          36. range
          37. raw_input
          38. reduce
          39. reload
          40. repr
          41. round
          42. setattr
          43. slice
          44. unichr
          45. vars
          46. xrange
          47. zip
        3. The sys Module
          1. argv
          2. displayhook
          3. excepthook
          4. exc_info
          5. exit
          6. getdefaultencoding
          7. getrefcount
          8. getrecursionlimit
          9. _getframe
          10. maxint
          11. modules
          12. path
          13. platform
          14. ps1, ps2
          15. setdefaultencoding
          16. setprofile
          17. setrecursionlimit
          18. settrace
          19. stdin, stdout, stderr
          20. tracebacklimit
          21. version
        4. The getopt Module
          1. getopt
        5. The copy Module
          1. copy
          2. deepcopy
        6. The bisect Module
          1. bisect
          2. insort
        7. The UserList, UserDict, and UserString Modules
      6. 9. Strings and Regular Expressions
        1. Methods of String Objects
          1. capitalize
          2. center
          3. count
          4. encode
          5. endswith
          6. expandtabs
          7. find
          8. index
          9. isalnum
          10. isalpha
          11. isdigit
          12. islower
          13. isspace
          14. istitle
          15. isupper
          16. join
          17. ljust
          18. lower
          19. lstrip
          20. replace
          21. rfind
          22. rindex
          23. rjust
          24. rstrip
          25. split
          26. splitlines
          27. startswith
          28. strip
          29. swapcase
          30. title
          31. translate
          32. upper
        2. The string Module
          1. Locale Sensitivity
          2. The maketrans Function
            1. maketrans
        3. String Formatting
          1. Format Specifier Syntax
          2. Common String-Formatting Idioms
        4. The pprint Module
          1. pformat
          2. pprint
        5. The repr Module
          1. repr
        6. Unicode
          1. The codecs Module
            1. EncodedFile
            2. open
          2. The unicodedata Module
        7. Regular Expressions and the re Module
          1. Pattern-String Syntax
          2. Common Regular Expression Idioms
          3. Sets of Characters
          4. Alternatives
          5. Groups
          6. Optional Flags
          7. Match Versus Search
          8. Anchoring at String Start and End
          9. Regular Expression Objects
            1. findall
            2. match
            3. search
            4. split
            5. sub
            6. subn
          10. Match Objects
            1. end, span, start
            2. expand
            3. group
            4. groups
            5. groupdict
          11. Functions of Module re
            1. compile
            2. escape
    4. III. Python Library and Extension Modules
      1. 10. File and Text Operations
        1. The os Module
          1. OSError Exceptions
          2. The errno Module
        2. Filesystem Operations
          1. Path-String Attributes of the os Module
          2. Permissions
          3. File and Directory Functions of the os Module
            1. access
            2. chdir
            3. chmod
            4. getcwd
            5. listdir
            6. makedirs, mkdir
            7. remove, unlink
            8. removedirs
            9. rename
            10. renames
            11. rmdir
            12. stat
            13. tempnam, tmpnam
            14. utime
          4. The os.path Module
            1. abspath
            2. basename
            3. commonprefix
            4. dirname
            5. exists
            6. expandvars
            7. getatime, getmtime, getsize
            8. isabs
            9. isfile
            10. isdir
            11. islink
            12. ismount
            13. join
            14. normcase
            15. normpath
            16. split
            17. splitdrive
            18. splitext
            19. walk
          5. The stat Module
            1. S_IFMT
            2. S_IMODE
          6. The filecmp Module
            1. cmp
            2. cmpfiles
            3. dircmp
          7. The shutil Module
            1. copy
            2. copy2
            3. copyfile
            4. copyfileobj
            5. copymode
            6. copystat
            7. copytree
            8. rmtree
          8. File Descriptor Operations
            1. close
            2. dup
            3. dup2
            4. fdopen
            5. fstat
            6. lseek
            7. open
            8. pipe
            9. read
            10. write
        3. File Objects
          1. Creating a File Object with open
            1. File mode
            2. Binary and text modes
            3. Buffering
            4. Sequential and non-sequential access
          2. Attributes and Methods of File Objects
            1. close
            2. closed
            3. flush
            4. isatty
            5. fileno
            6. mode
            7. name
            8. read
            9. readline
            10. readlines
            11. seek
            12. softspace
            13. tell
            14. truncate
            15. write
            16. writelines
            17. xreadlines
          3. Iteration on File Objects
          4. File-Like Objects and Polymorphism
        4. Auxiliary Modules for File I/O
          1. The fileinput Module
            1. close
            2. FileInput
            3. filelineno
            4. filename
            5. input
            6. isfirstline
            7. isstdin
            8. lineno
            9. nextfile
          2. The linecache Module
            1. checkcache
            2. clearcache
            3. getline
          3. The struct Module
            1. calcsize
            2. pack
            3. unpack
          4. The xreadlines Module
            1. xreadlines
        5. The StringIO and cStringIO Modules
          1. StringIO
          2. getvalue
        6. Compressed Files
          1. The gzip Module
            1. GzipFile
            2. open
          2. The zipfile Module
            1. is_zipfile
            2. ZipInfo
            3. ZipFile
            4. close
            5. getinfo
            6. infolist
            7. namelist
            8. printdir
            9. read
            10. testzip
            11. write
            12. writestr
          3. The zlib Module
            1. compress
            2. decompress
        7. Text Input and Output
          1. Standard Output and Standard Error
          2. The print Statement
          3. Standard Input
          4. The getpass Module
            1. getpass
            2. getuser
        8. Richer-Text I/O
          1. The readline Module
            1. get_history_length
            2. parse_and_bind
            3. read_history_file
            4. read_init_file
            5. set_completer
            6. set_history_length
            7. write_history_file
          2. Console I/O
            1. The curses package
              1. wrapper
              2. addstr
              3. clrtobot, clrtoeol
              4. delch
              5. deleteln
              6. erase
              7. getch
              8. getyx
              9. insstr
              10. move
              11. nodelay
              12. refresh
              13. Textpad
            2. The msvcrt module
              1. getch, getche
              2. kbhit
              3. ungetch
            3. The WConio and Console modules
        9. Interactive Command Sessions
          1. Methods of Cmd Instances
            1. cmdloop
            2. default
            3. do_help
            4. emptyline
            5. onecmd
            6. postcmd
            7. postloop
            8. precmd
            9. preloop
          2. Attributes of Cmd Instances
          3. A Cmd Example
        10. Internationalization
          1. The locale Module
            1. atof
            2. atoi
            3. format
            4. getdefaultlocale
            5. getlocale
            6. localeconv
            7. normalize
            8. resetlocale
            9. setlocale
            10. str
            11. strcoll
            12. strxfrm
          2. The gettext Module
            1. Using gettext for localization
            2. Essential gettext functions
              1. install
              2. translation
      2. 11. Persistence and Databases
        1. Serialization
          1. The marshal Module
            1. dump, dumps
            2. load, loads
          2. The pickle and cPickle Modules
            1. Functions of pickle and cPickle
              1. dump, dumps
              2. load, loads
              3. Pickler
              4. Unpickler
            2. A pickling example
            3. Pickling instance objects
            4. Pickling customization with the copy_reg module
              1. constructor
              2. pickle
          3. The shelve Module
        2. DBM Modules
          1. The anydbm Module
            1. open
          2. The dumbdbm Module
          3. The dbm, gdbm, and dbhash Modules
          4. The whichdb Module
            1. whichdb
          5. Examples of DBM-Like File Use
        3. The Berkeley DB Module
          1. Reference Section
            1. btopen, hashopen, rnopen
          2. Reference Section
            1. close
          3. Reference Section
            1. first
          4. Reference Section
            1. has_key
          5. Reference Section
            1. keys
          6. Reference Section
            1. last
          7. Reference Section
            1. next
          8. Reference Section
            1. previous
          9. Reference Section
            1. set_location
          10. Examples of Berkeley DB Use
        4. The Python Database API (DBAPI) 2.0
          1. Exception Classes
          2. Thread Safety
          3. Parameter Style
          4. Factory Functions
            1. Binary
            2. Date
            3. DateFromTicks
            4. Time
            5. TimeFromTicks
            6. Timestamp
            7. TimestampFromTicks
          5. Type Description Attributes
          6. The connect Function
          7. Connection Objects
            1. close
            2. commit
            3. cursor
            4. rollback
          8. Cursor Objects
            1. close
            2. description
            3. execute
            4. executemany
            5. fetchall
            6. fetchmany
            7. fetchone
            8. rowcount
          9. DBAPI-Compliant Modules
          10. Gadfly
            1. gadfly
            2. gfclient
      3. 12. Time Operations
        1. The time Module
          1. asctime
          2. clock
          3. ctime
          4. gmtime
          5. localtime
          6. mktime
          7. sleep
          8. strftime
          9. strptime
          10. time
          11. timezone
          12. tzname
        2. The sched Module
          1. scheduler
          2. cancel
          3. empty
          4. enterabs
          5. enter
          6. run
        3. The calendar Module
          1. calendar
          2. firstweekday
          3. isleap
          4. leapdays
          5. month
          6. monthcalendar
          7. monthrange
          8. prcal
          9. prmonth
          10. setfirstweekday
          11. timegm
          12. weekday
        4. The mx.DateTime Module
          1. Date and Time Types
          2. The DateTime Type
            1. Factory functions for DateTime
              1. DateTime, Date, Timestamp
              2. DateTimeFrom, TimestampFrom
              3. DateTimeFromAbsDays
              4. DateTimeFromCOMDate
              5. DateFromTicks
              6. gmt, utc
              7. gmtime, utctime
              8. localtime
              9. mktime
              10. now
              11. TimestampFromTicks
              12. today
            2. Methods of DateTime instances
              1. absvalues
              2. COMDate
              3. gmticks
              4. gmtime
              5. gmtoffset
              6. localtime
              7. strftime, Format
              8. ticks
              9. tuple
            3. Attributes of DateTime instances
            4. Arithmetic on DateTime instances
          3. The DateTimeDelta Type
            1. Factory functions for DateTimeDelta
              1. DateTimeDelta
              2. DateTimeDeltaFrom
              3. DateTimeDeltaFromSeconds
              4. TimeDelta, Time
              5. TimeDeltaFrom, TimeFrom
              6. TimeFromTicks
            2. Methods of DateTimeDelta instances
              1. absvalues
              2. strftime, Format
              3. tuple
            3. Attributes of DateTimeDelta instances
            4. Arithmetic on DateTimeDelta instances
          4. Other Attributes
            1. cmp
          5. Submodules
      4. 13. Controlling Execution
        1. Dynamic Execution and the exec Statement
          1. Avoiding exec
          2. Restricting Execution
          3. Expressions
          4. Compile and Code Objects
        2. Restricted Execution
          1. The rexec Module
              1. RExec
            1. Methods
              1. r_add_module
              2. r_eval, s_eval
              3. r_exec, s_exec
              4. r_execfile, s_execfile
              5. r_import, s_import
              6. r_open
              7. r_reload, s_reload
              8. r_unload, s_unload
            2. Attributes
            3. Using rexec
          2. The Bastion Module
            1. Bastion
        3. Internal Types
          1. Type Objects
          2. The Code Object Type
          3. The frame Type
        4. Garbage Collection
          1. The gc Module
            1. collect
            2. disable
            3. enable
            4. garbage
            5. get_debug
            6. get_objects
            7. get_referrers
            8. get_threshold
            9. isenabled
            10. set_debug
            11. set_threshold
          2. The weakref Module
            1. getweakrefcount
            2. getweakrefs
            3. proxy
            4. ref
            5. WeakKeyDictionary
            6. WeakValueDictionary
        5. Termination Functions
          1. register
        6. Site and User Customization
          1. The site and sitecustomize Modules
          2. User Customization
      5. 14. Threads and Processes
        1. Threads in Python
        2. The thread Module
          1. acquire
          2. locked
          3. release
        3. The Queue Module
          1. Queue
          2. Empty
          3. Full
          4. empty
          5. full
          6. get, get_nowait
          7. put, put_nowait
          8. qsize
        4. The threading Module
          1. Reference Section
            1. currentThread
          2. Thread Objects
            1. Thread
            2. getName, setName
            3. isAlive
            4. isDaemon, setDaemon
            5. join
            6. run
            7. start
          3. Thread Synchronization Objects
            1. Timeout parameters
            2. Lock and RLock objects
            3. Condition objects
              1. Condition
              2. acquire, release
              3. notify, notifyAll
              4. wait
            4. Event objects
              1. Event
              2. clear
              3. isSet
              4. set
              5. wait
            5. Semaphore objects
              1. Semaphore
              2. acquire
              3. release
        5. Threaded Program Architecture
        6. Process Environment
        7. Running Other Programs
          1. execl, execle, execlp, execv, execve, execvp, execvpe
          2. popen
          3. popen2, popen3, popen4
          4. spawnv, spawnve
          5. system
        8. The mmap Module
          1. Reference Section
            1. mmap
          2. Methods of mmap Objects
            1. close
            2. find
            3. flush
            4. move
            5. read
            6. read_byte
            7. readline
            8. resize
            9. seek
            10. size
            11. tell
            12. write
            13. write_byte
          3. Using mmap Objects for IPC
      6. 15. Numeric Processing
        1. The math and cmath Modules
          1. acos
          2. acosh
          3. asin
          4. asinh
          5. atan
          6. atanh
          7. atan2
          8. ceil
          9. cos
          10. cosh
          11. e
          12. exp
          13. fabs
          14. floor
          15. fmod
          16. frexp
          17. hypot
          18. ldexp
          19. log
          20. log10
          21. modf
          22. pi
          23. pow
          24. sin
          25. sinh
          26. sqrt
          27. tan
          28. tanh
        2. The operator Module
        3. The random Module
          1. choice
          2. getstate
          3. jumpahead
          4. random
          5. randrange
          6. seed
          7. setstate
          8. shuffle
          9. uniform
        4. The array Module
          1. array
          2. byteswap
          3. fromfile
          4. fromlist
          5. fromstring
          6. tofile
          7. tolist
          8. tostring
        5. The Numeric Package
        6. Array Objects
          1. Type Codes
          2. Shape and Indexing
          3. Storage
          4. Slicing
            1. Slicing examples
            2. Assigning to array slices
          5. Truth Values
          6. Factory Functions
            1. array
            2. arrayrange, arange
            3. fromstring
            4. identity
            5. ones
            6. zeros
          7. Attributes and Methods
            1. astype
            2. byteswapped
            3. copy
            4. flat
            5. imag, imaginary, real
            6. iscontiguous
            7. itemsize
            8. savespace
            9. shape
            10. spacesaver
            11. tolist
            12. tostring
            13. typecode
          8. Operations on Arrays
            1. Broadcasting
            2. In-place operations
          9. Functions
            1. allclose
            2. argmax, argmin
            3. argsort
            4. array2string
            5. average
            6. choose
            7. clip
            8. compress
            9. concatenate
            10. convolve
            11. cross_correlate
            12. diagonal
            13. indices
            14. innerproduct
            15. matrixmultiply
            16. nonzero
            17. put
            18. putmask
            19. rank
            20. ravel
            21. repeat
            22. reshape
            23. resize
            24. searchsorted
            25. shape
            26. size
            27. sort
            28. swapaxes
            29. take
            30. trace
            31. transpose
            32. where
        7. Universal Functions (ufuncs)
          1. The Optional output Argument
          2. Callable Attributes
            1. accumulate
            2. outer
            3. reduce
            4. reduceat
          3. ufunc Objects Supplied by Numeric
          4. Shorthand for Commonly Used ufunc Methods
        8. Optional Numeric Modules
      7. 16. Tkinter GUIs
        1. Tkinter Fundamentals
        2. Widget Fundamentals
          1. Common Widget Options
            1. Color options
            2. Length options
            3. Options expressing numbers of characters
            4. Other common options
          2. Common Widget Methods
            1. cget
            2. config
            3. focus_set
            4. grab_set,grab_release
            5. mainloop
            6. quit
            7. update
            8. update_idletasks
            9. wait_variable
            10. wait_visibility
            11. wait_window
            12. winfo_height
            13. winfo_width
          3. Tkinter Variable Objects
          4. Tkinter Images
        3. Commonly Used Simple Widgets
          1. Button
            1. flash
            2. invoke
          2. Checkbutton
            1. deselect
            2. flash
            3. invoke
            4. select
            5. toggle
          3. Entry
          4. Label
          5. Listbox
            1. curselection
            2. select_clear
            3. select_set
          6. Radiobutton
            1. deselect
            2. flash
            3. invoke
            4. select
          7. Scale
            1. get
            2. set
          8. Scrollbar
        4. Container Widgets
          1. Frame
          2. Toplevel
            1. deiconify
            2. geometry
            3. iconify
            4. maxsize
            5. minsize
            6. overrideredirect
            7. protocol
            8. resizable
            9. state
            10. title
            11. withdraw
        5. Menus
          1. Menu-Specific Methods
            1. add, add_cascade, add_checkbutton, add_command, add_radiobutton, add_separator
            2. delete
            3. entryconfigure, entryconfig
            4. insert, insert_cascade, insert_checkbutton, insert_command, insert_radiobutton, insert_separator
            5. invoke
            6. post
            7. unpost
          2. Menu Entries
          3. Menu Example
        6. The Text Widget
          1. Text Widget Methods
            1. delete
            2. get
            3. image_create
            4. insert
            5. search
            6. see
            7. window_create
            8. xview, yview
          2. Giving Text a Scrollbar
          3. Marks
            1. mark_gravity
            2. mark_set
            3. mark_unset
          4. Tags
            1. tag_add
            2. tag_bind
            3. tag_cget
            4. tag_config
            5. tag_delete
            6. tag_lower
            7. tag_names
            8. tag_raise
            9. tag_ranges
            10. tag_remove
            11. tag_unbind
          5. Indices
            1. compare
            2. index
          6. Fonts
            1. actual
            2. cget
            3. config
            4. copy
          7. Text Example
        7. The Canvas Widget
          1. Canvas Methods on Items
            1. bbox
            2. coords
            3. delete
            4. gettags
            5. itemcget
            6. itemconfig
            7. tag_bind
            8. tag_unbind
          2. The Line Canvas Item
            1. create_line
          3. The Polygon Canvas Item
            1. create_polygon
          4. The Rectangle Canvas Item
            1. create_rectangle
          5. The Text Canvas Item
            1. create_text
          6. A Simple Plotting Example
        8. Geometry Management
          1. The Packer
            1. pack
            2. pack_forget
            3. pack_info
          2. The Gridder
            1. grid
            2. grid_forget
            3. grid_info
          3. The Placer
            1. place
            2. place_forget
            3. place_info
        9. Tkinter Events
          1. The Event Object
          2. Binding Callbacks to Events
          3. Event Names
            1. Keyboard events
            2. Mouse events
          4. Event-Related Methods
            1. bind
            2. bind_all
            3. unbind
            4. unbind_all
          5. An Events Example
          6. Other Callback-Related Methods
            1. after
            2. after_cancel
            3. after_idle
      8. 17. Testing, Debugging, and Optimizing
        1. Testing
          1. Unit Testing and System Testing
          2. The doctest Module
          3. The unittest Module
            1. The TestCase class
              1. assert_, failUnless
              2. assertEqual, failUnlessEqual
              3. assertNotEqual, failIfEqual
              4. assertRaises, failUnlessRaises
              5. fail
              6. failIf
              7. setUp
              8. tearDown
            2. Unit tests dealing with large amounts of data
        2. Debugging
          1. The inspect Module
            1. getargspec, formatargspec
            2. getargvalues, formatargvalues
            3. currentframe
            4. getdoc
            5. getfile, getsourcefile
            6. getmembers
            7. getmodule
            8. getmro
            9. getsource, getsourcelines
            10. isbuiltin,isclass,iscode, isframe, isfunction, ismethod, ismodule, isroutine
            11. stack
          2. The traceback Module
            1. print_exc
          3. The pdb Module
            1. !
            2. alias, unalias
            3. args, a
            4. break, b
            5. clear, cl
            6. condition
            7. continue, c, cont
            8. disable
            9. down, d
            10. enable
            11. ignore
            12. list, l
            13. next, n
            14. p
            15. quit, q
            16. return, r
            17. step, s
            18. tbreak
            19. up, u
            20. where, w
          4. Debugging in IDLE
        3. The warnings Module
          1. Classes
          2. Objects
          3. Filters
          4. Functions
            1. filterwarnings
            2. formatwarning
            3. resetwarnings
            4. showwarning
            5. warn
        4. Optimization
          1. Developing a Fast-Enough Python Application
          2. Benchmarking
          3. Large-Scale Optimization
            1. List operations
            2. String operations
            3. Dictionary operations
          4. Profiling
            1. The profile module
              1. run
            2. Calibration
              1. calibrate
            3. The pstats module
              1. Stats
              2. add
              3. print_callees, print_callers
              4. print_stats
              5. sort_stats
              6. strip_dirs
          5. Small-Scale Optimization
            1. Building up a string from pieces
            2. Searching and sorting
            3. Avoiding exec and from ... import *
            4. Optimizing loops
            5. Optimizing I/O
    5. IV. Network and Web Programming
      1. 18. Client-Side Network Protocol Modules
        1. URL Access
          1. The urlparse Module
            1. urljoin
            2. urlsplit
            3. urlunsplit
          2. The urllib Module
            1. Functions
              1. quote
              2. quote_plus
              3. unquote
              4. unquote_plus
              5. urlcleanup
              6. urlencode
              7. urlopen
              8. urlretrieve
            2. The FancyURLopener class
              1. prompt_user_passwd
              2. version
          3. The urllib2 Module
            1. Functions
              1. build_opener
              2. install_opener
              3. urlopen
            2. The Request class
              1. Request
              2. add_data
              3. add_header
              4. get_data
              5. get_full_url
              6. get_host
              7. get_selector
              8. get_type
              9. has_data
              10. set_proxy
            3. The OpenerDirector class
            4. Handler classes
            5. Handling authentication
              1. add_password
        2. Email Protocols
          1. The poplib Module
            1. POP3
            2. dele
            3. list
            4. pass_
            5. quit
            6. retr
            7. set_debuglevel
            8. stat
            9. top
            10. user
          2. The smtplib Module
            1. SMTP
            2. connect
            3. login
            4. quit
            5. sendmail
        3. The HTTP and FTP Protocols
          1. The httplib Module
            1. HTTPConnection
            2. close
            3. getresponse
            4. request
          2. The ftplib Module
            1. FTP
            2. connect
            3. cwd
            4. delete
            5. login
            6. mkd
            7. pwd
            8. quit
            9. rename
            10. retrbinary
            11. retrlines
            12. rmd
            13. sendcmd
            14. set_pasv
            15. size
            16. storbinary
            17. storlines
        4. Network News
          1. Reference Section
            1. NNTP
          2. Response Strings
          3. Methods
            1. article
            2. body
            3. group
            4. head
            5. last
            6. list
            7. newgroups
            8. newnews
            9. next
            10. post
            11. quit
            12. stat
          4. Example
        5. Telnet
          1. Telnet
          2. close
          3. expect
          4. interact
          5. open
          6. read_all
          7. read_eager
          8. read_some
          9. read_until
          10. write
        6. Distributed Computing
          1. binary
          2. boolean
          3. Binary
          4. Boolean
          5. DateTime
          6. ServerProxy
      2. 19. Sockets and Server-Side Network Protocol Modules
        1. The socket Module
          1. socket Functions
            1. getfqdn
            2. gethostbyaddr
            3. gethostbyname_ex
            4. htonl
            5. htons
            6. inet_aton
            7. inet_ntoa
            8. ntohl
            9. ntohs
            10. socket
          2. The socket Class
            1. accept
            2. bind
            3. close
            4. connect
            5. getpeername
            6. listen
            7. makefile
            8. recv
            9. recvfrom
            10. send
            11. sendall
            12. sendto
          3. Echo Server and Client Using TCP Sockets
          4. Echo Server and Client Using UDP Sockets
          5. The timeoutsocket Module
            1. get_timeout
            2. set_timeout
            3. getDefaultSocketTimeout
            4. setDefaultSocketTimeout
        2. The SocketServer Module
          1. The BaseRequestHandler Class
            1. client_address
            2. handle
            3. request
            4. server
          2. HTTP Servers
            1. The BaseHTTPServer module
              1. command
              2. handle
              3. end_headers
              4. path
              5. rfile
              6. send_header
              7. send_error
              8. send_response
              9. wfile
            2. The SimpleHTTPServer module
            3. The CGIHTTPServer module
            4. The SimpleXMLRPCServer module
              1. register_function
              2. register_instance
        3. Event-Driven Socket Programs
          1. The select Module
            1. select
          2. The asyncore and asynchat Modules
            1. The asyncore module
              1. loop
              2. create_socket
              3. handle_accept
              4. handle_close
              5. handle_connect
              6. handle_read
              7. handle_write
              8. send
            2. The asynchat module
              1. collect_incoming_data
              2. found_terminator
              3. push
              4. set_terminator
          3. The Twisted Framework
            1. The twisted.internet and twisted.protocols packages
            2. Reactors
              1. callLater
              2. cancelCallLater
              3. listenTCP
              4. run
              5. stop
            3. Transports
              1. getHost
              2. getPeer
              3. loseConnection
              4. write
            4. Protocol handlers and factories
              1. connectionLost
              2. connectionMade
              3. dataReceived
            5. Echo server using twisted
      3. 20. CGI Scripting and Alternatives
        1. CGI in Python
          1. Form Submission Methods
          2. The cgi Module
            1. escape
            2. FieldStorage
            3. getfirst
            4. getlist
            5. getvalue
          3. CGI Output and Errors
            1. Error messages
            2. The cgitb module
              1. handle
              2. enable
          4. Installing Python CGI Scripts
            1. Python CGI scripts on Microsoft web servers
            2. Python CGI scripts on Apache
            3. Python CGI scripts on Xitami
        2. Cookies
          1. The Cookie Module
              1. Morsel
              2. SimpleCookie
              3. SmartCookie
            1. Cookie methods
              1. js_output
              2. load
              3. output
            2. Morsel attributes and methods
              1. js_output
              2. output
              3. OutputString
              4. set
            3. Using module Cookie
        3. Other Server-Side Approaches
          1. FastCGI
          2. LRWP
          3. PyApache and mod_python
          4. Webware
          5. Quixote
          6. Custom Pure Python Servers
      4. 21. MIME and Network Encodings
        1. Encoding Binary Data as Text
          1. The base64 Module
            1. decode
            2. decodestring
            3. encode
            4. encodestring
          2. The quopri Module
            1. decode
            2. decodestring
            3. encode
            4. encodestring
          3. The uu Module
            1. decode
            2. encode
        2. MIME and Email Format Handling
          1. Functions in Package email
            1. message_from_string
            2. message_from_file
          2. The email.Message Module
            1. add_header
            2. add_payload
            3. as_string
            4. epilogue
            5. get_all
            6. get_boundary
            7. get_charsets
            8. get_filename
            9. get_maintype
            10. get_param
            11. get_params
            12. get_payload
            13. get_subtype
            14. get_type
            15. get_unixfrom
            16. is_multipart
            17. preamble
            18. set_boundary
            19. set_payload
            20. set_unixfrom
            21. walk
          3. The email.Generator Module
            1. Generator
          4. Creating Messages
            1. MIMEAudio
            2. MIMEBase
            3. MIMEImage
            4. MIMEMessage
            5. MIMEText
          5. The email.Encoders Module
            1. encode_base64
            2. encode_noop
            3. encode_quopri
            4. encode_7or8bit
          6. The email.Utils Module
            1. decode
            2. dump_address_pair
            3. encode
            4. formatdate
            5. getaddresses
            6. mktime_tz
            7. parseaddr
            8. parsedate
            9. parsedate_tz
            10. quote
            11. unquote
          7. The Message Classes of the rfc822 and mimetools Modules
            1. getmaintype
            2. getparam
            3. getsubtype
            4. gettype
      5. 22. Structured Text: HTML
        1. The sgmllib Module
          1. close
          2. do_tag
          3. end_tag
          4. feed
          5. handle_charref
          6. handle_comment
          7. handle_data
          8. handle_endtag
          9. handle_entityref
          10. handle_starttag
          11. report_unbalanced
          12. start_tag
          13. unknown_charref
          14. unknown_endtag
          15. unknown_entityref
          16. unknown_starttag
        2. The htmllib Module
          1. Reference Section
            1. anchor_bgn
          2. Reference Section
            1. anchor_end
          3. Reference Section
            1. anchorlist
          4. Reference Section
            1. formatter
          5. Reference Section
            1. handle_image
          6. Reference Section
            1. nofill
          7. Reference Section
            1. save_bgn
          8. Reference Section
            1. save_end
          9. The formatter Module
            1. AbstractFormatter
            2. AbstractWriter
            3. DumbWriter
            4. NullFormatter
            5. NullWriter
          10. The htmlentitydefs Module
          11. Parsing HTML with htmllib
        3. The HTMLParser Module
          1. close
          2. feed
          3. handle_charref
          4. handle_comment
          5. handle_data
          6. handle_endtag
          7. handle_entityref
          8. handle_starttag
        4. Generating HTML
          1. Embedding
          2. Templating
          3. The Cheetah Package
            1. The Cheetah templating language
            2. The Template class
              1. Template
            3. A Cheetah example
      6. 23. Structured Text: XML
        1. An Overview of XML Parsing
        2. Parsing XML with SAX
          1. The xml.sax Package
              1. make_parser
              2. parse
              3. parseString
              4. ContentHandler
            1. Attributes
              1. getValueByQName
              2. getNameByQName
              3. getQNameByName
              4. getQNames
            2. Incremental parsing
              1. close
              2. feed
              3. reset
            3. The xml.sax.saxutils module
              1. escape
              2. quoteattr
              3. XMLGenerator
          2. Parsing XHTML with xml.sax
        3. Parsing XML with DOM
          1. The xml.dom Package
          2. The xml.dom.minidom Module
              1. parse
              2. parseString
            1. Node objects
              1. attributes
              2. childNodes
              3. firstChild
              4. hasChildNodes
              5. isSameNode
              6. lastChild
              7. localName
              8. namespaceURI
              9. nextSibling
              10. nodeName
              11. nodeType
              12. nodeValue
              13. normalize
              14. ownerDocument
              15. parentNode
              16. prefix
              17. previousSibling
            2. Attr objects
              1. ownerElement
              2. specified
            3. Document objects
              1. doctype
              2. documentElement
              3. getElementById
              4. getElementsByTagName
              5. getElementsByTagNameNS
            4. Element objects
              1. getAttribute
              2. getAttributeNS
              3. getAttributeNode
              4. getAttributeNodeNS
              5. getElementsByTagName
              6. getElementsByTagNameNS
              7. hasAttribute
              8. hasAttributeNS
          3. Parsing XHTML with xml.dom.minidom
          4. The xml.dom.pulldom Module
            1. parse
            2. parseString
            3. expandNode
          5. Parsing XHTML with xml.dom.pulldom
        4. Changing and Generating XML
          1. Factory Methods of a Document Object
            1. createComment
            2. createElement
            3. createTextNode
          2. Mutating Methods of an Element Object
            1. removeAttribute
            2. setAttribute
          3. Mutating Methods of a Node Object
            1. appendChild
            2. insertBefore
            3. removeChild
            4. replaceChild
          4. Output Methods of a Node Object
            1. toprettyxml
            2. toxml
            3. writexml
          5. Changing and Outputting XHTML with xml.dom.minidom
    6. V. Extending and Embedding
      1. 24. Extending and Embedding Classic Python
        1. Extending Python with Python’s C API
          1. Building and Installing C-Coded Python Extensions
          2. Overview of C-Coded Python Extension Modules
          3. Return Values of Python’s C API Functions
          4. Module Initialization
            1. Py_InitModule3
            2. PyModule_AddIntConstant
            3. PyModule_AddObject
            4. PyModule_AddStringConstant
            5. PyModule_GetDict
            6. PyImport_Import
          5. Reference Counting
          6. Accessing Arguments
            1. PyArg_ParseTuple
            2. PyArg_ParseTupleAndKeywords
          7. Creating Python Values
            1. Py_BuildValue
          8. Exceptions
            1. PyErr_Format
            2. PyErr_NewException
            3. PyErr_NoMemory
            4. PyErr_SetObject
            5. PyErr_SetFromErrno
            6. PyErr_SetFromErrnoWithFilename
            7. PyErr_Clear
            8. PyErr_ExceptionMatches
            9. PyErr_Occurred
            10. PyErr_Print
          9. Abstract Layer Functions
            1. PyCallable_Check
            2. PyEval_CallObject
            3. PyEval_CallObjectWithKeywords
            4. PyIter_Check
            5. PyIter_Next
            6. PyNumber_Check
            7. PyObject_CallFunction
            8. PyObject_CallMethod
            9. PyObject_Cmp
            10. PyObject_DelAttrString
            11. PyObject_DelItem
            12. PyObject_DelItemString
            13. PyObject_GetAttrString
            14. PyObject_GetItem
            15. PyObject_GetItemString
            16. PyObject_GetIter
            17. PyObject_HasAttrString
            18. PyObject_IsTrue
            19. PyObject_Length
            20. PyObject_Repr
            21. PyObject_RichCompare
            22. PyObject_RichCompareBool
            23. PyObject_SetAttrString
            24. PyObject_SetItem
            25. PyObject_SetItemString
            26. PyObject_Str
            27. PyObject_Type
            28. PyObject_Unicode
            29. PySequence_Contains
            30. PySequence_DelSlice
            31. PySequence_Fast
            32. PySequence_Fast_GET_ITEM
            33. PySequence_Fast_GET_SIZE
            34. PySequence_GetSlice
            35. PySequence_List
            36. PySequence_SetSlice
            37. PySequence_Tuple
            38. PyNumber_Power
          10. Concrete Layer Functions
            1. PyDict_GetItem
            2. PyDict_GetItemString
            3. PyDict_Next
            4. PyDict_Merge
            5. PyDict_MergeFromSeq2
            6. PyFloat_AS_DOUBLE
            7. PyList_New
            8. PyList_GET_ITEM
            9. PyList_SET_ITEM
            10. PyString_AS_STRING
            11. PyString_AsStringAndSize
            12. PyString_FromFormat
            13. PyString_FromStringAndSize
            14. PyTuple_New
            15. PyTuple_GET_ITEM
            16. PyTuple_SET_ITEM
          11. A Simple Extension Example
          12. Defining New Types
            1. Per-instance data
            2. The PyTypeObject definition
            3. Instance initialization and finalization
            4. Attribute access
            5. Type definition example
        2. Extending Python Without Python’s C API
        3. Embedding Python
          1. Installing Resident Extension Modules
            1. PyImport_AppendInittab
          2. Setting Arguments
            1. Py_SetProgramName
            2. PySys_SetArgv
          3. Python Initialization and Finalization
            1. Py_Finalize
            2. Py_Initialize
          4. Running Python Code
            1. PyRun_File
            2. PyRun_String
            3. PyModule_New
            4. Py_CompileString
            5. PyEval_EvalCode
      2. 25. Extending and Embedding Jython
        1. Importing Java Packages in Jython
          1. The Jython Registry
          2. Accessibility
          3. Type Conversions
            1. Calling overloaded Java methods
            2. The jarray module
              1. array
              2. zeros
            3. The java.util collection classes
          4. Subclassing a Java Class
          5. JavaBeans
        2. Embedding Jython in Java
          1. The PythonInterpreter Class
            1. eval
            2. exec
            3. execfile
            4. get
            5. set
          2. The PyObject Class
          3. The Py Class
        3. Compiling Python into Java
          1. The jythonc command
          2. Adding Java-Visible Methods
          3. Python Applets and Servlets
            1. Python applets
            2. Python servlets
      3. 26. Distributing Extensions and Programs
        1. Python’s distutils
          1. The Distribution and Its Root
          2. The setup.py Script
          3. Metadata About the Distribution
          4. Distribution Contents
            1. Python source files
              1. packages
              2. py_modules
              3. scripts
            2. Other files
              1. data_files
            3. C-coded extensions
              1. ext_modules
              2. Extension
          5. The setup.cfg File
          6. The MANIFEST.in and MANIFEST Files
          7. Creating Prebuilt Distributions with distutils
        2. The py2exe Tool
        3. The Installer Tool
    7. Index
    8. Colophon

Product information

  • Title: Python in a Nutshell
  • Author(s):
  • Release date: March 2003
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9780596001889