Log In
Or create an account -> 
Imperial Library
  • Home
  • About
  • News
  • Upload
  • Forum
  • Help
  • Login/SignUp

Index
Python in a Nutshell, 2nd Edition Preface
How This Book Is Organized
Part I, Getting Started with Python Part II, Core Python Language and Built-ins Part III, Python Library and Extension Modules Part IV, Network and Web Programming Part V, Extending and Embedding
Conventions Used in This Book
Reference Conventions Typographic Conventions
Using Code Examples How to Contact Us SafariĀ® Enabled Acknowledgments
I. Getting Started with Python
1. Introduction to Python
1.1. The Python Language 1.2. The Python Standard Library and Extension Modules 1.3. Python Implementations
1.3.1. CPython 1.3.2. Jython 1.3.3. IronPython 1.3.4. Choosing Between CPython, Jython, and IronPython 1.3.5. PyPy and Other Experimental Versions 1.3.6. Licensing and Price Issues
1.4. Python Development and Versions 1.5. Python Resources
1.5.1. Documentation 1.5.2. Newsgroups and Mailing Lists 1.5.3. Special-Interest Groups 1.5.4. Python Business Forum 1.5.5. Python Journal 1.5.6. Extension Modules and Python Sources 1.5.7. The Python Cookbook 1.5.8. Books and Magazines
2. Installation
2.1. Installing Python from Source Code
2.1.1. Windows
2.1.1.1. Uncompressing and unpacking the Python source code 2.1.1.2. Building the Python source code with Microsoft Visual Studio 2003 2.1.1.3. Building Python for debugging 2.1.1.4. Installing after the build 2.1.1.5. Building Python for Cygwin
2.1.2. Unix-Like Platforms
2.1.2.1. Uncompressing and unpacking the Python source code 2.1.2.2. Configuring, building, and testing 2.1.2.3. Installing after the build
2.2. Installing Python from Binaries
2.2.1. Apple Macintosh
2.3. Installing Jython 2.4. Installing IronPython
3. The Python Interpreter
3.1. The python Program
3.1.1. Environment Variables 3.1.2. Command-Line Syntax and Options 3.1.3. Interactive Sessions
3.2. Python Development Environments
3.2.1. IDLE 3.2.2. Other Free Cross-Platform Python IDEs 3.2.3. Platform-Specific Free Python IDEs 3.2.4. Commercial Python IDEs 3.2.5. Free Text Editors with Python Support 3.2.6. Tools for Checking Python Programs
3.3. Running Python Programs 3.4. The jython Interpreter 3.5. The IronPython Interpreter
II. Core Python Language and Built-ins
4. The Python Language
4.1. Lexical Structure
4.1.1. Lines and Indentation 4.1.2. Character Sets 4.1.3. Tokens
4.1.3.1. Identifiers 4.1.3.2. Keywords 4.1.3.3. Operators 4.1.3.4. Delimiters 4.1.3.5. Literals
4.1.4. Statements
4.1.4.1. Simple statements 4.1.4.2. Compound statements
4.2. Data Types
4.2.1. Numbers
4.2.1.1. Integer numbers 4.2.1.2. Floating-point numbers 4.2.1.3. Complex numbers
4.2.2. Sequences
4.2.2.1. Iterables 4.2.2.2. Strings 4.2.2.3. Tuples 4.2.2.4. Lists
4.2.3. Sets 4.2.4. Dictionaries 4.2.5. None 4.2.6. Callables 4.2.7. Boolean Values
4.3. Variables and Other References
4.3.1. Variables
4.3.1.1. Object attributes and items 4.3.1.2. Accessing nonexistent references
4.3.2. Assignment Statements
4.3.2.1. Plain assignment 4.3.2.2. Augmented assignment
4.3.3. del Statements
4.4. Expressions and Operators
4.4.1. Comparison Chaining 4.4.2. Short-Circuiting Operators
4.4.2.1. The Python 2.5 ternary operator
4.5. Numeric Operations
4.5.1. Numeric Conversions 4.5.2. Arithmetic Operations
4.5.2.1. Division 4.5.2.2. Exponentiation
4.5.3. Comparisons 4.5.4. Bitwise Operations on Integers
4.6. Sequence Operations
4.6.1. Sequences in General
4.6.1.1. Sequence conversions 4.6.1.2. Concatenation and repetition 4.6.1.3. Membership testing 4.6.1.4. Indexing a sequence 4.6.1.5. Slicing a sequence
4.6.2. Strings 4.6.3. Tuples 4.6.4. Lists
4.6.4.1. Modifying a list 4.6.4.2. In-place operations on a list 4.6.4.3. List methods 4.6.4.4. Sorting a list
4.7. Set Operations
4.7.1. Set Membership 4.7.2. Set Methods
4.8. Dictionary Operations
4.8.1. Dictionary Membership 4.8.2. Indexing a Dictionary 4.8.3. Dictionary Methods
4.9. The print Statement 4.10. Control Flow Statements
4.10.1. The if Statement 4.10.2. The while Statement 4.10.3. The for Statement
4.10.3.1. Iterators 4.10.3.2. range and xrange 4.10.3.3. List comprehensions
4.10.4. The break Statement 4.10.5. The continue Statement 4.10.6. The else Clause on Loop Statements 4.10.7. The pass Statement 4.10.8. The try and raise Statements 4.10.9. The with Statement
4.11. Functions
4.11.1. The def Statement 4.11.2. Parameters 4.11.3. Attributes of Function Objects
4.11.3.1. Docstrings 4.11.3.2. Other attributes of function objects
4.11.4. The return Statement 4.11.5. Calling Functions
4.11.5.1. The semantics of argument passing 4.11.5.2. Kinds of arguments
4.11.6. Namespaces
4.11.6.1. The global statement 4.11.6.2. Nested functions and nested scopes
4.11.7. lambda Expressions 4.11.8. Generators
4.11.8.1. Generator expressions 4.11.8.2. Generators in Python 2.5
4.11.9. Recursion
5. Object-Oriented Python
5.1. Classes and Instances
5.1.1. Python Classes 5.1.2. The class Statement 5.1.3. The Class Body
5.1.3.1. Attributes of class objects 5.1.3.2. Function definitions in a class body 5.1.3.3. Class-private variables 5.1.3.4. Class documentation strings
5.1.4. Descriptors
5.1.4.1. Overriding and nonoverriding descriptors
5.1.5. Instances
5.1.5.1. _ _init_ _ 5.1.5.2. Attributes of instance objects 5.1.5.3. The factory-function idiom 5.1.5.4. _ _new_ _
5.1.6. Attribute Reference Basics
5.1.6.1. Getting an attribute from a class 5.1.6.2. Getting an attribute from an instance 5.1.6.3. Setting an attribute
5.1.7. Bound and Unbound Methods
5.1.7.1. Unbound method details 5.1.7.2. Bound method details
5.1.8. Inheritance
5.1.8.1. Method resolution order 5.1.8.2. Overriding attributes 5.1.8.3. Delegating to superclass methods 5.1.8.4. Cooperative superclass method calling 5.1.8.5. "Deleting" class attributes
5.1.9. The Built-in object Type 5.1.10. Class-Level Methods
5.1.10.1. Static methods 5.1.10.2. Class methods
5.1.11. Properties
5.1.11.1. Why properties are important 5.1.11.2. Properties and inheritance
5.1.12. _ _slots_ _ 5.1.13. _ _getattribute_ _ 5.1.14. Per-Instance Methods 5.1.15. Inheritance from Built-in Types
5.2. Special Methods
5.2.1. General-Purpose Special Methods
_ _call_ _ _ _cmp_ _ _ _del_ _ _ _delattr_ _ _ _eq_ _, _ _ge_ _, _ _gt_ _, _ _le_ _, _ _lt_ _, _ _ne_ _ _ _getattr_ _ _ _get-attribute_ _ _ _hash_ _ _ _init_ _ _ _new_ _ _ _nonzero_ _ _ _repr_ _ _ _setattr_ _ _ _str_ _ _ _unicode_ _
5.2.2. Special Methods for Containers
5.2.2.1. Sequences 5.2.2.2. Mappings 5.2.2.3. Sets 5.2.2.4. Container slicing 5.2.2.5. Container methods
_ _contains_ _ _ _delitem_ _ _ _getitem_ _ _ _iter_ _ _ _len_ _ _ _setitem_ _
5.2.3. Special Methods for Numeric Objects
_ _abs_ _, _ _invert_ _, _ _neg_ _, _ _pos_ _ _ _add_ _, _ _div_ _, _ _floordiv_ _, _ _mod_ _, _ _mul_ _, _ _sub_ _, _ _truediv_ _ _ _and_ _, _ _lshift_ _, _ _or_ _, _ _rshift_ _, _ _xor_ _ _ _coerce_ _ _ _complex_ _, _ _float_ _, _ _int_ _, _ _long_ _ _ _divmod_ _ _ _hex_ _, _ _oct_ _ _ _iadd_ _, _ _idiv_ _, _ _ifloordiv_ _, _ _imod_ _, _ _imul_ _, _ _isub_ _, _ _itruediv_ _ _ _iand_ _, _ _ilshift_ _, _ _ior_ _, _ _irshift_ _, _ _ixor_ _ _ _index_ _ _ _ipow_ _ _ _pow_ _ _ _radd_ _, _ _rdiv_ _, _ _rmod_ _, _ _rmul_ _, _ _rsub_ _ _ _rand_ _, _ _rlshift_ _, _ _ror_ _, _ _rrshift_ _, _ _rxor_ _ _ _rdivmod_ _ _ _rpow_ _
5.3. Decorators 5.4. Metaclasses
5.4.1. How Python Determines a Class's Metaclass 5.4.2. How a Metaclass Creates a Class
5.4.2.1. Defining and using your own metaclasses 5.4.2.2. A substantial custom metaclass example
6. Exceptions
6.1. The try Statement
6.1.1. try/except 6.1.2. try/finally 6.1.3. Python 2.5 Exception-Related Enhancements
6.1.3.1. The try/except/finally statement 6.1.3.2. The with statement 6.1.3.3. Generator enhancements
6.2. Exception Propagation 6.3. The raise Statement 6.4. Exception Objects
6.4.1. The Hierarchy of Standard Exceptions 6.4.2. Standard Exception Classes
6.5. Custom Exception Classes
6.5.1. Custom Exceptions and Multiple Inheritance 6.5.2. Other Exceptions Used in the Standard Library
6.6. Error-Checking Strategies
6.6.1. LBYL Versus EAFP
6.6.1.1. Proper usage of EAFP
6.6.2. Handling Errors in Large Programs 6.6.3. Logging Errors
6.6.3.1. The logging module
6.6.4. The assert Statement
6.6.4.1. The _ _debug_ _ built-in variable
7. Modules
7.1. Module Objects
7.1.1. The import Statement
7.1.1.1. Module body 7.1.1.2. Attributes of module objects 7.1.1.3. Python built-ins 7.1.1.4. Module documentation strings 7.1.1.5. Module-private variables
7.1.2. The from Statement
7.1.2.1. The from...import * statement 7.1.2.2. from versus import
7.2. Module Loading
7.2.1. Built-in Modules 7.2.2. Searching the Filesystem for a Module 7.2.3. The Main Program 7.2.4. The reload Function 7.2.5. Circular Imports 7.2.6. sys.modules Entries 7.2.7. Custom Importers
7.2.7.1. Rebinding _ _import_ _ 7.2.7.2. Import hooks
7.3. Packages
7.3.1.
7.3.1.1. Special attributes of package objects
7.3.2. Absolute Versus Relative Imports
7.4. The Distribution Utilities (distutils)
7.4.1. Python Eggs
8. Core Built-ins
8.1. Built-in Types
basestring bool buffer classmethod complex dict enumerate file, open float frozenset int list long object property reversed set slice staticmethod strstr super tuple type unicode xrange
8.2. Built-in Functions
_ _import_ _ abs all any callable chr cmp coerce compile delattr dir divmod eval execfile filter getattr globals hasattr hash hex id input intern isinstance issubclass iter len locals map max min oct ord pow range raw_input reduce reload repr round setattr sorted sum unichr vars zip
8.3. The sys Module
argv displayhook excepthook exc_info exit getdefaulten-coding getrefcount getrecursionlimit _getframe maxint modules path platform ps1, ps2 setdefaultencoding setprofile setrecursionlimit settrace stdin,stdin stdout,stdout stderrstderr tracebacklimit version
8.4. The copy Module
copy deepcopy
8.5. The collections Module
8.5.1. deque
append appendleft clear extend extendleft pop popleft rotate
8.5.2. defaultdict
8.6. The functional Module
partial
8.7. The bisect Module
bisect insort
8.8. The heapq Module
heapify heappop heappush heapreplace nlargest nsmallest
8.9. The UserDict Module 8.10. The optparse Module
add_option parse_args
8.11. The itertools Module
chain count cycle ifilter imap islice izip repeat tee
9. Strings and Regular Expressions
9.1. Methods of String Objects
capitalize center count decode encode endswith expandtabs find index isalnum isalpha isdigit islower isspace istitle isupper join ljust lower lstrip replace rfind rindex rjust rstrip split splitlines startswith strip swapcase title translate upper
9.2. The string Module
9.2.1. Locale Sensitivity 9.2.2. The maketrans Function
maketrans
9.3. String Formatting
9.3.1. Format Specifier Syntax 9.3.2. Common String-Formatting Idioms 9.3.3. Template Strings
Template safe_substitute substitute
9.3.4. Text Wrapping and Filling
wrap fill
9.4. The pprint Module
pformat pprint
9.5. The repr Module
repr
9.6. Unicode
9.6.1. The codecs Module
register_error
EncodedFile open
9.6.2. The unicodedata Module
9.7. Regular Expressions and the re Module
9.7.1. Pattern-String Syntax 9.7.2. Common Regular Expression Idioms 9.7.3. Sets of Characters 9.7.4. Alternatives 9.7.5. Groups 9.7.6. Optional Flags 9.7.7. Match Versus Search 9.7.8. Anchoring at String Start and End 9.7.9. Regular Expression Objects
findall finditer match search split sub subn
9.7.10. Match Objects
end, span, start expand group groups groupdict
9.7.11. Functions of Module re
compile escape
III. Python Library and Extension Modules
10. File and Text Operations
10.1. Other Chapters That Also Deal with Files 10.2. Organization of This Chapter 10.3. File Objects
10.3.1. Creating a File Object with open
10.3.1.1. File mode 10.3.1.2. Binary and text modes 10.3.1.3. Buffering 10.3.1.4. Sequential and nonsequential access
10.3.2. Attributes and Methods of File Objects
close closed encoding flush isatty fileno mode name newlines read readline readlines seek softspace tell truncate write writelines
10.3.3. Iteration on File Objects 10.3.4. File-Like Objects and Polymorphism 10.3.5. The tempfile Module
mkstemp mkdtemp TemporaryFile NamedTempor-aryFile
10.4. Auxiliary Modules for File I/O
10.4.1. The fileinput Module
close FileInput filelineno filename input isfirstline isstdin lineno nextfile
10.4.2. The linecache Module
checkcache clearcache getline getlines
10.4.3. The struct Module
calcsize pack unpack
10.5. The StringIO and cStringIO Modules
StringIO getvalue
10.6. Compressed Files
10.6.1. The gzip Module
GzipFile open
10.6.2. The bz2 Module
BZ2File compress decompress
10.6.3. The tarfile Module
is_tarfile TarInfo open add addfile close extract extractfile getmember getmembers getnames gettarinfo list
10.6.4. The zipfile Module
is_zipfile ZipInfo ZipFile close getinfo infolist namelist printdir read testzip write writestr
10.6.5. The zlib Module
compress decompress
10.7. The os Module
10.7.1. OSError Exceptions 10.7.2. The errno Module
10.8. Filesystem Operations
10.8.1. Path-String Attributes of the os Module 10.8.2. Permissions 10.8.3. File and Directory Functions of the os Module
access chdir chmod getcwd listdir makedirs, mkdir remove, unlink removedirs rename renames rmdir stat tempnam, tmpnam utime walk
10.8.4. The os.path Module
abspath basename commonprefix dirname exists expandvars getatime, getmtime, getsize isabs isfile isdir islink ismount join normcase normpath split splitdrive splitext walk
10.8.5. The stat Module
S_IFMT S_IMODE
10.8.6. The filecmp Module
cmp cmpfiles dircmp
10.8.7. The shutil Module
copy copy2 copyfile copyfileobj copymode copystat copytree move rmtree
10.8.8. File Descriptor Operations
close dup dup2 fdopen fstat lseek open pipe read write
10.9. Text Input and Output
10.9.1. Standard Output and Standard Error 10.9.2. The print Statement 10.9.3. Standard Input 10.9.4. The getpass Module
getpass getuser
10.10. Richer-Text I/O
10.10.1. The readline Module
add_history clear_history get_completer get_history_length parse_and_bind read_history_file read_init_file set_completer set_history_length write_history_file
10.10.2. Console I/O
10.10.2.1. The curses package
wrapper addstr clrtobot, clrtoeol delch deleteln erase getch getyx insstr move nodelay refresh Textpad
10.10.2.2. The msvcrt Module
getch, getche kbhit ungetch
10.10.2.3. The WConio and Console modules
10.11. Interactive Command Sessions
10.11.1. Initializing a Cmd Instance
_ _init_ _
10.11.2. Methods of Cmd Instances
cmdloop default do_help emptyline onecmd postcmd postloop precmd preloop
10.11.3. Attributes of Cmd Instances 10.11.4. A Cmd Example
10.12. Internationalization
10.12.1. The locale Module
atof atoi format getdefaultlocale getlocale localeconv normalize resetlocale setlocale strstr strcoll strxfrm
10.12.2. The gettext Module
10.12.2.1. Using gettext for localization 10.12.2.2. Essential gettext functions
install translation
10.12.3. More Internationalization Resources
11. Persistence and Databases
11.1. Serialization
11.1.1. The marshal Module
dump, dumps load, loads
11.1.1.1. A marshaling example
11.1.2. The pickle and cPickle Modules
11.1.2.1. Functions of pickle and cPickle
dump, dumps load, loads Pickler Unpickler
11.1.2.2. A pickling example 11.1.2.3. Pickling instances 11.1.2.4. Pickling customization with the copy_reg module
constructor pickle
11.1.3. The shelve Module
11.1.3.1. A shelving example
11.2. DBM Modules
11.2.1. The anydbm Module
open
11.2.2. The dumbdbm Module 11.2.3. The dbm, gdbm, and dbhash Modules 11.2.4. The whichdb Module
whichdb
11.2.5. Examples of DBM-Like File Use
11.3. Berkeley DB Interfacing
11.3.1. Simplified and Complete BSD DB Python Interfaces 11.3.2. Module bsddb
btopen, hashopen, rnopen close first has_key keys last next previous set_location
11.3.3. Examples of Berkeley DB Use
11.4. The Python Database API (DBAPI) 2.0
11.4.1. Exception Classes 11.4.2. Thread Safety 11.4.3. Parameter Style 11.4.4. Factory Functions
Binary Date DateFromTicks Time TimeFromTicks Timestamp Timestamp-FromTicks
11.4.5. Type Description Attributes 11.4.6. The connect Function 11.4.7. Connection Objects
close commit cursor rollback
11.4.8. Cursor Objects
close description execute executemany fetchall fetchmany fetchone rowcount
11.4.9. DBAPI-Compliant Modules 11.4.10. Gadfly
gadfly gfclient
11.4.11. SQLite
12. Time Operations
12.1. The time Module
asctime clock ctime gmtime localtime mktime sleep strftime strptime time timezone tzname
12.2. The datetime Module
12.2.1. Class date
date fromordinal fromtimestamp today ctime isocalendar isoformat isoweekday replace strftime timetuple toordinal weekday
12.2.2. Class time
time isoformat replace strftime
12.2.3. Class datetime
datetime combine fromordinal fromtimestamp now today utcfromtime-stamp utcnow astimezone ctime date isocalendar isoformat isoweekday replace strftime time timetz timetuple toordinal utctimetuple weekday
12.2.4. Class timedelta
timedelta
12.3. The pytz Module
country_timezones timezone
12.4. The dateutil Module
easter parser relativedelta rrule after before between count
12.5. The sched Module
scheduler cancel empty enterabs enter run
12.6. The calendar Module
calendar firstweekday isleap leapdays month monthcalendar monthrange prcal prmonth setfirstweekday timegm weekday
12.7. The mx.DateTime Module
12.7.1. Date and Time Types 12.7.2. The DateTime Type
12.7.2.1. Factory functions for DateTime
DateTime, Date, Timestamp DateTimeFrom, TimestampFrom DateTime-FromAbsDays DateTime-FromCOMDate DateFromTicks gmt, utc gmtime, utctime localtime mktime now Timestamp-FromTicks today
12.7.2.2. Methods of DateTime instances
absvalues COMDate gmticks gmtime gmtoffset localtime strftime, Format ticks tuple
12.7.2.3. Attributes of DateTime instances 12.7.2.4. Arithmetic on DateTime instances
12.7.3. The DateTimeDelta Type
12.7.3.1. Factory functions for DateTimeDelta
DateTimeDelta DateTimeDelta-From DateTimeDelta-FromSeconds TimeDelta, Time TimeDeltaFrom, TimeFrom TimeFromTicks
12.7.3.2. Methods of DateTimeDelta instances
absvalues strftime, Format tuple
12.7.3.3. Attributes of DateTimeDelta instances 12.7.3.4. Arithmetic on DateTimeDelta instances
12.7.4. Other Attributes
cmp
12.7.5. Submodules
13. Controlling Execution
13.1. Dynamic Execution and the exec Statement
13.1.1. Avoiding exec 13.1.2. Expressions 13.1.3. Compile and Code Objects 13.1.4. Never exec nor eval Untrusted Code
13.2. Internal Types
13.2.1. Type Objects 13.2.2. The Code Object Type 13.2.3. The frame Type
13.3. Garbage Collection
13.3.1. The gc Module
collect disable enable garbage get_debug get_objects get_referrers get_threshold isenabled set_debug set_threshold
13.3.2. The weakref Module
getweakrefcount getweakrefs proxy ref WeakKeyDic-tionary WeakValueDic-tionary
13.4. Termination Functions
register
13.5. Site and User Customization
13.5.1. The site and sitecustomize Modules 13.5.2. User Customization
14. Threads and Processes
14.1. Threads in Python 14.2. The thread Module
acquire locked release
14.3. The Queue Module
Queue Empty Full
14.3.1. Methods of Queue Instances
empty full get, get_nowait put, put_nowait qsize
14.3.2. Customizing Class Queue by Subclassing
14.4. The threading Module
currentThread
14.4.1. Thread Objects
Thread getName, setName isAlive isDaemon, setDaemon join run start
14.4.2. Thread Synchronization Objects
14.4.2.1. Timeout parameters 14.4.2.2. Lock and RLock objects 14.4.2.3. Condition objects
Condition acquire, release notify, notifyAll wait
14.4.2.4. Event objects
Event clear isSet set wait
14.4.2.5. Semaphore objects
Semaphore acquire release
14.4.3. Thread Local Storage
14.5. Threaded Program Architecture 14.6. Process Environment 14.7. Running Other Programs
14.7.1. Running Other Programs with the os Module
execl, execle, execlp, execv, execve, execvp, execvpe popen popen2, popen3, popen4 spawnv, spawnve system
14.7.2. The Subprocess Module
Popen
14.7.2.1. What to run, and how: args, executable, shell 14.7.2.2. Subprocess files: stdin, stdout, stderr, bufsize, universal_newlines, close_fds 14.7.2.3. Other arguments: preexec_fn, cwd, env, startupinfo, creationflags 14.7.2.4. Attributes of subprocess.Popen instances 14.7.2.5. Methods of subprocess.Popen instances
communicate poll wait
14.8. The mmap Module
mmap
14.8.1. Methods of mmap Objects
close find flush move read read_byte readline resize seek size tell write write_byte
14.8.2. Using mmap Objects for IPC
15. Numeric Processing
15.1. The math and cmath Modules 15.2. The operator Module
attrgetter itemgetter
15.3. Random and Pseudorandom Numbers
15.3.1.
15.3.1.1. Physically random and cryptographically strong random numbers
urandom
15.3.1.2. The random module
choice getrandbits getstate jumpahead random randrange sample seed setstate shuffle uniform
15.4. The decimal Module 15.5. The gmpy Module
16. Array Processing
16.1. The array Module
array byteswap fromfile fromlist fromstring tofile tolist tostring
16.2. Extensions for Numeric Array Computation 16.3. The Numeric Package 16.4. Array Objects
16.4.1. Typecodes 16.4.2. Shape and Indexing 16.4.3. Storage 16.4.4. Slicing
16.4.4.1. Slicing examples 16.4.4.2. Assigning to array slices
16.4.5. Truth Values and Comparisons of Arrays 16.4.6. Factory Functions
array, asarray arrayrange, arange fromstring identity empty ones zeros
16.4.7. Attributes and Methods
astype byteswapped copy flat imag, imaginary, real iscontiguous itemsize savespace shape spacesaver tolist toscalar tostring typecode
16.4.8. Operations on Arrays
16.4.8.1. Broadcasting 16.4.8.2. In-place operations
16.4.9. Functions
allclose argmax, argmin argsort around array2string average choose clip compress concatenate convolve cross_correlate diagonal dot indices innerproduct matrixmultiply nonzero outerproduct put putmask rank ravel repeat reshape resize searchsorted shape size sort swapaxes take trace transpose vdot where
16.5. Universal Functions (ufuncs)
16.5.1. The Optional output Argument 16.5.2. Callable Attributes
accumulate outer reduce reduceat
16.5.3. ufunc Objects Supplied by Numeric 16.5.4. Shorthand for Commonly Used ufunc Methods
16.6. Auxiliary Numeric Modules
17. Tkinter GUIs
17.1. Tkinter Fundamentals
17.1.1. Dialogs
17.1.1.1. The tkMessageBox module 17.1.1.2. The tkSimpleDialog module 17.1.1.3. The tkFileDialog module 17.1.1.4. The tkColorChooser module
17.2. Widget Fundamentals
17.2.1. Common Widget Options
17.2.1.1. Color options 17.2.1.2. Length options 17.2.1.3. Options expressing numbers of characters 17.2.1.4. Other common options
17.2.2. Common Widget Methods
cget config focus_set grab_set, grab_release mainloop quit update update_idletasks wait_variable wait_visibility wait_window winfo_height winfo_width
17.2.3. Tkinter Variable Objects 17.2.4. Tkinter Images
17.3. Commonly Used Simple Widgets
17.3.1. Button
flash invoke
17.3.2. Checkbutton
deselect flash invoke select toggle
17.3.3. Entry 17.3.4. Label 17.3.5. Listbox
curselection select_clear select_set
17.3.6. Radiobutton
deselect flash invoke select
17.3.7. Scale
get set
17.3.8. Scrollbar
17.4. Container Widgets
17.4.1. Frame 17.4.2. Toplevel
deiconify geometry iconify maxsize minsize overrideredirect protocol resizable state title withdraw
17.5. Menus
17.5.1. Menu-Specific Methods
add, add_cascade, add_checkbutton, add_command, add_radiobutton, add_separator delete entryconfigure, entryconfig insert, insert_cascade, insert_checkbutton, insert_command, insert_radiobutton, insert_separator invoke post unpost
17.5.2. Menu Entries 17.5.3. Menu Example
17.6. The Text Widget
17.6.1. The ScrolledText Module 17.6.2. Text Widget Methods
delete get image_create insert search see window_create xview, yview
17.6.3. Marks
mark_gravity mark_set mark_unset
17.6.4. Tags
tag_add tag_bind tag_cget tag_config tag_delete tag_lower tag_names tag_raise tag_ranges tag_remove tag_unbind
17.6.5. Indices
compare index
17.6.6. Fonts
actual cget config copy
17.6.7. Text Example
17.7. The Canvas Widget
17.7.1. Canvas Methods on Items
bbox coords delete gettags itemcget itemconfig tag_bind tag_unbind
17.7.2. The Line Canvas Item
create_line
17.7.3. The Polygon Canvas Item
create_polygon
17.7.4. The Rectangle Canvas Item
create_rectangle
17.7.5. The Text Canvas Item
create_text
17.7.6. A Simple Plotting Example
17.8. Layout Management
17.8.1. The Packer
pack pack_forget pack_info
17.8.2. The Gridder
grid grid_forget grid_info
17.8.3. The Placer
place place_forget place_info
17.9. Tkinter Events
17.9.1. The Event Object 17.9.2. Binding Callbacks to Events 17.9.3. Event Names
17.9.3.1. Keyboard events 17.9.3.2. Mouse events
17.9.4. Event-Related Methods
bind bind_all unbind unbind_all
17.9.5. An Events Example 17.9.6. Other Callback-Related Methods
after after_cancel after_idle
18. Testing, Debugging, and Optimizing
18.1. Testing
18.1.1. Unit Testing and System Testing 18.1.2. The doctest Module 18.1.3. The unittest Module
18.1.3.1. The TestCase class
assert_, failUnless assertAlmost-Equal, failUnlessAl-mostEqual assertEqual, failUnlessEqual assertNotAl-mostEqual, failIfAlmost-Equal assertNotEqual, failIfEqual assertRaises, failUnlessRaises fail failIf setUp tearDown
18.1.3.2. Unit tests dealing with large amounts of data
18.2. Debugging
18.2.1. Before You Debug 18.2.2. The inspect Module
getargspec, formatargspec getargvalues, formatarg-values currentframe getdoc getfile, getsourcefile getmembers getmodule getmro getsource, getsourcelines isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule, isroutine stack
18.2.2.1. An example of using inspect
18.2.3. The traceback Module
print_exc
18.2.4. The pdb Module
! alias, unalias args, a break, b clear, cl condition continue, c, cont disable down, d enable ignore list, l next, n print, p quit, q return, r step, s tbreak up, u where, w
18.2.5. Debugging in IDLE
18.3. The warnings Module
18.3.1. Classes 18.3.2. Objects 18.3.3. Filters 18.3.4. Functions
filterwarnings formatwarning resetwarnings showwarning warn
18.4. Optimization
18.4.1. Developing a Fast-Enough Python Application 18.4.2. Benchmarking 18.4.3. Large-Scale Optimization
18.4.3.1. List operations 18.4.3.2. String operations 18.4.3.3. Dictionary operations 18.4.3.4. Set operations 18.4.3.5. Summary of big-O times for operations on Python built-in types
18.4.4. Profiling
18.4.4.1. The profile module
run
18.4.4.2. Calibration
calibrate
18.4.4.3. The pstats module
Stats add print_callees, print_callers print_stats sort_stats strip_dirs
18.4.5. Small-Scale Optimization
18.4.5.1. Module timeit 18.4.5.2. Building up a string from pieces 18.4.5.3. Searching and sorting 18.4.5.4. Avoiding exec and from...import * 18.4.5.5. Optimizing loops 18.4.5.6. Optimizing I/O
IV. Network and Web Programming
19. Client-Side Network Protocol Modules
19.1. URL Access
19.1.1. The urlparse Module
urljoin urlsplit urlunsplit
19.1.2. The urllib Module
19.1.2.1. Functions
quote quote_plus unquote unquote_plus urlcleanup urlencode urlopen urlretrieve
19.1.2.2. The FancyURLopener class
prompt_user_passwd version
19.1.3. The urllib2 Module
19.1.3.1. Functions
build_opener install_opener urlopen
19.1.3.2. The Request class
Request add_data add_header add_unredirec-ted_header get_data get_full_url get_host get_method get_selector get_type has_data has_header set_proxy
19.1.3.3. The OpenerDirector class 19.1.3.4. Handler classes 19.1.3.5. Handling authentication
add_password
19.2. Email Protocols
19.2.1. The poplib Module
POP3 dele list pass_ quit retr set_debuglevel stat top user
19.2.2. The smtplib Module
SMTP connect login quit sendmail
19.3. The HTTP and FTP Protocols
19.3.1. The httplib Module
HTTPConnection close getresponse request
19.3.2. The ftplib Module
FTP abort connect cwd delete getwelcome login mkd pwd quit rename retrbinary retrlines rmd sendcmd set_pasv size storbinary storlines
19.4. Network News
NNTP
19.4.1. Response Strings 19.4.2. Methods
article body group head last list newgroups newnews next post quit stat
19.4.3. Example
19.5. Telnet
Telnet close expect interact open read_all read_eager read_some read_until write
19.6. Distributed Computing
Binary DateTime ServerProxy
19.7. Other Protocols
20. Sockets and Server-Side Network Protocol Modules
20.1. The socket Module
20.1.1. socket Functions
getdefault-timeout getfqdn gethostbyaddr gethostby-name_ex htonl htons inet_aton inet_ntoa ntohl ntohs setdefault-timeout socket
20.1.2. The socket Class
accept bind close connect getpeername getsockname getsockopt gettimeout listen makefile recv recvfrom send sendall sendto
20.1.3. Echo Server and Client Using TCP Sockets 20.1.4. Echo Server and Client Using UDP Sockets 20.1.5. Socket Timeout Behavior
20.2. The SocketServer Module
20.2.1. The BaseRequestHandler Class
client_address handle request server
20.2.2. HTTP Servers
20.2.2.1. The BaseHTTPServer module
command handle end_headers path rfile send_header send_error send_response wfile
20.2.2.2. The SimpleHTTPServer module 20.2.2.3. The CGIHTTPServer module 20.2.2.4. The SimpleXMLRPCServer module
register_function register_instance
20.3. Event-Driven Socket Programs
20.3.1. The select Module
select
20.3.2. The asyncore and asynchat Modules
20.3.2.1. The asyncore module
loop create_socket handle_accept handle_close handle_connect handle_read handle_write send
20.3.2.2. The asynchat module
collect_incoming_data found_terminator push set_terminator
20.3.3. The Twisted Framework
20.3.3.1. The twisted.internet and twisted.protocols packages 20.3.3.2. Reactors
callLater callInThread callFromThread callWhenRun-ning connectTCP listenTCP run stop
20.3.3.3. Transports
getHost getPeer loseConnection write writeSequence
20.3.3.4. Protocol handlers and factories
connectionLost connection-Made dataReceived makeConnec-tion
20.3.3.5. Echo server using Twisted
21. CGI Scripting and Alternatives
21.1. CGI in Python
21.1.1. Form Submission Methods 21.1.2. The cgi Module
escape FieldStorage getfirst getlist
21.1.3. CGI Output and Errors
21.1.3.1. Error messages 21.1.3.2. The cgitb module
handle enable
21.1.4. Installing Python CGI Scripts
21.1.4.1. Python CGI scripts on Microsoft web servers 21.1.4.2. Python CGI scripts on Apache 21.1.4.3. Python CGI scripts on Xitami
21.2. Cookies
21.2.1. The Cookie Module
Morsel SimpleCookie SmartCookie
21.2.1.1. Cookie methods
js_output load output
21.2.1.2. Morsel attributes and methods
js_output output OutputString set
21.2.1.3. Using module Cookie
21.3. Other Server-Side Approaches
21.3.1. FastCGI 21.3.2. WSGI 21.3.3. mod_python 21.3.4. Custom Pure Python Servers 21.3.5. Other Higher-Level-of-Abstraction Frameworks
21.3.5.1. Webware 21.3.5.2. Quixote 21.3.5.3. web.py
22. MIME and Network Encodings
22.1. Encoding Binary Data as Text
22.1.1. The base64 Module
decode decodestring encode encodestring
22.1.2. The quopri Module
decode decodestring encode encodestring
22.1.3. The uu Module
decode encode
22.2. MIME and Email Format Handling
22.2.1. Functions in Package email
message_from_string message_from_file
22.2.2. The email.Message Module
add_header as_string attach epilogue get_all get_boundary get_charsets get_content_maintype get_content_subtype get_content_type get_filename get_param get_params get_payload get_unixfrom is_multipart preamble set_boundary set_payload set_unixfrom walk
22.2.3. The email.Generator Module
Generator
22.2.4. Creating Messages
MIMEAudio MIMEBase MIMEImage MIMEMessage MIMEText
22.2.5. The email.Encoders Module
encode_base64 encode_noop encode_quopri encode_7or8bit
22.2.6. The email.Utils Module
formataddr formatdate getaddresses mktime_tz parseaddr parsedate parsedate_tz quote unquote
22.2.7. Example Uses of the email Package 22.2.8. The Message Classes of the rfc822 and mimetools Modules
getmaintype getparam getsubtype gettype
23. Structured Text: HTML
23.1. The sgmllib Module
close do_tag end_tag feed handle_charref handle_comment handle_data handle_endtag handle_entityref handle_starttag report_unbalanced start_tag unknown_charref unknown_endtag unknown_entityref unknown_starttag
23.1.1. Parsing HTML with sgmllib
23.2. The htmllib Module
anchor_bgn anchor_end anchorlist formatter handle_image nofill save_bgn save_end Abstract-Formatter AbstractWriter DumbWriter NullFormatter NullWriter
23.2.1. The htmlentitydefs Module 23.2.2. Parsing HTML with htmllib
23.3. The HTMLParser Module
close feed handle_charref handle_comment handle_data handle_endtag handle_entityref handle_starttag
23.3.1. Parsing HTML with HTMLParser
23.4. The BeautifulSoup Extension
23.4.1. Parsing HTML with BeautifulSoup
23.5. Generating HTML
23.5.1. Embedding 23.5.2. Templating 23.5.3. The Cheetah Package
23.5.3.1. The Cheetah templating language 23.5.3.2. The Template class
Template
23.5.3.3. A Cheetah example
24. Structured Text: XML
24.1. An Overview of XML Parsing 24.2. Parsing XML with SAX
24.2.1. The xml.sax Package
make_parser parse parseString ContentHandler
24.2.1.1. Attributes
getValueByQ-Name etNameByQ-Name getQNameBy-Name getQNames
24.2.1.2. Incremental parsing
close feed reset
24.2.1.3. The xml.sax.saxutils module
escape quoteattr XMLGenerator
24.2.2. Parsing XHTML with xml.sax
24.3. Parsing XML with DOM
24.3.1. The xml.dom Package 24.3.2. The xml.dom.minidom Module
parse parseString
24.3.2.1. Node objects
attributes childNodes firstChild hasChildNodes isSameNode lastChild localName namespaceURI nextSibling nodeName nodeType nodeValue normalize ownerDocument parentNode prefix previousSibling
24.3.2.2. Attr objects
ownerElement specified
24.3.2.3. Document objects
doctype document-Element getElementById getElementsBy-TagName getElementsBy-TagNameNS
24.3.2.4. Element objects
getAttribute getAttributeNS getAttribute-Node getAttribute-NodeNS getElementsBy-TagName getElementsBy-TagNameNS hasAttribute hasAttributeNS
24.3.3. Parsing XHTML with xml.dom.minidom 24.3.4. The xml.dom.pulldom Module
parse parseString expandNode
24.3.5. Parsing XHTML with xml.dom.pulldom
24.4. Changing and Generating XML
24.4.1. Factory Methods of a Document Object
createComment createElement createTextNode
24.4.2. Mutating Methods of an Element Object
removeAttribute setAttribute
24.4.3. Mutating Methods of a Node Object
appendChild insertBefore removeChild replaceChild
24.4.4. Output Methods of a Node Object
toprettyxml toxml writexml
24.4.5. Changing and Outputting XHTML with xml.dom.minidom
V. Extending and Embedding
25. Extending and Embedding Classic Python
25.1. Extending Python with Python's C API
25.1.1. Building and Installing C-Coded Python Extensions
25.1.1.1. The C compiler you need 25.1.1.2. Compatibility of C-coded extensions among Python versions
25.1.2. Overview of C-Coded Python Extension Modules 25.1.3. Return Values of Python's C API Functions 25.1.4. Module Initialization
Py_InitModule3 PyModule_AddIntConstant PyModule_AddObject PyModule_AddStringCon-stant PyModule_GetDict PyImport_Import
25.1.4.1. The PyMethodDef structure
25.1.5. Reference Counting 25.1.6. Accessing Arguments
PyArg_ParseTuple
PyArg_ParseTupleAndKeywords
25.1.7. Creating Python Values
Py_BuildValue
25.1.8. Exceptions
PyErr_Format PyErr_NewException PyErr_NoMemory PyErr_SetObject PyErr_SetFromErrno PyErr_SetFromErrnoWithFilename PyErr_Clear PyErr_ExceptionMatches PyErr_Occurred PyErr_Print
25.1.9. Abstract Layer Functions
PyCallable_Check PyEval_CallObject PyEval_CallObjectWithKeywords PyIter_Check PyIter_Next PyNumber_Check PyObject_CallFunction PyObject_CallMethod PyObject_Cmp PyObject_DelAttrString PyObject_DelItem PyObject_DelItemString PyObject_GetAttrString PyObject_GetItem PyObject_GetItemString PyObject_GetIter PyObject_HasAttrString PyObject_IsTrue PyObject_Length PyObject_Repr PyObject_RichCompare PyObject_RichCompareBool PyObject_SetAttrString PyObject_SetItem PyObject_SetItemString PyObject_Str PyObject_Type PyObject_Unicode PySequence_Contains PySequence_DelSlice PySequence_Fast PySequence_Fast_GET_ITEM PySequence_Fast_GET_SIZE PySequence_GetSlice PySequence_List PySequence_SetSlice PySequence_Tuple PyNumber_Power
25.1.10. Concrete Layer Functions
PyDict_GetItem PyDict_GetItemString PyDict_Next PyDict_Merge PyDict_MergeFromSeq2 PyFloat_AS_DOUBLE PyList_New PyList_GET_ITEM PyList_SET_ITEM PyString_AS_STRING PyString_AsStringAndSize PyString_FromFormat PyString_FromStringAnd-Size PyTuple_New PyTuple_GET_ITEM PyTuple_SET_ITEM
25.1.11. A Simple Extension Example 25.1.12. Defining New Types
25.1.12.1. Per-instance data 25.1.12.2. The PyTypeObject definition 25.1.12.3. Instance initialization and finalization 25.1.12.4. Attribute access 25.1.12.5. Type definition example
25.2. Extending Python Without Python's C API 25.3. Embedding Python
25.3.1. Installing Resident Extension Modules
PyImport_AppendInittab
25.3.2. Setting Arguments
Py_SetPro-gramName PySys_SetArgv
25.3.3. Python Initialization and Finalization
Py_Finalize Py_Initialize
25.3.4. Running Python Code
PyRun_File PyRun_String PyModule_New Py_CompileString PyEval_EvalCode
25.4. Pyrex
25.4.1. The cdef Statement and Function Parameters
25.4.1.1. External declarations 25.4.1.2. cdef classes
25.4.2. The ctypedef Statement 25.4.3. The for...from Statement 25.4.4. Pyrex Expressions 25.4.5. A Pyrex Example: Greatest Common Divisor
26. Extending and Embedding Jython
26.1. Importing Java Packages in Jython
26.1.1. The Jython Registry 26.1.2. Accessibility 26.1.3. Type Conversions
26.1.3.1. Calling overloaded Java methods 26.1.3.2. The jarray module
array zeros
26.1.3.3. The java.util collection classes
26.1.4. Subclassing a Java Class 26.1.5. JavaBeans
26.2. Embedding Jython in Java
26.2.1. The PythonInterpreter Class
eval exec execfile get set
26.2.1.1. The _ _builtin_ _ class
26.2.2. The PyObject Class 26.2.3. The Py Class
26.3. Compiling Python into Java
26.3.1. The jythonc Command 26.3.2. Adding Java-Visible Methods 26.3.3. Python Applets and Servlets
26.3.3.1. Python applets 26.3.3.2. Python servlets
27. Distributing Extensions and Programs
27.1. Python's distutils
27.1.1. The Distribution and Its Root 27.1.2. The setup.py Script 27.1.3. Metadata About the Distribution 27.1.4. Distribution Contents
27.1.4.1. Python source files
packages py_modules scripts
27.1.4.2. Datafiles
data_files
27.1.4.3. C-coded extensions
ext_modules Extension
27.1.5. The setup.cfg File 27.1.6. The MANIFEST.in and MANIFEST Files 27.1.7. Creating Prebuilt Distributions with distutils
27.2. py2exe 27.3. py2app 27.4. cx_Freeze 27.5. PyInstaller
Index About the Author Colophon Copyright
  • ← Prev
  • Back
  • Next →
  • ← Prev
  • Back
  • Next →

Chief Librarian: Las Zenow <zenow@riseup.net>
Fork the source code from gitlab
.

This is a mirror of the Tor onion service:
http://kx5thpx2olielkihfyo4jgjqfb7zx7wxr3sd4xzt26ochei4m6f7tayd.onion