A first draft python fact sheet, extracted from the Python Ref Manual

Kenneth Manheimer (klm@nist.gov)
Wed, 15 Jun 1994 23:50:21 GMT

I have just spent a day and a half going through the python reference
manual and extracting all the facts that seemed most useful, and
condensing them into an emacs 'allout' outline. The following
represents selectively exposed (and reformatted) portions of that
outline, in case it would be of interest to anyone else.

The outline version is a bit less than twice as long, in case anyone
else uses allout, and would find the outline version useful. I would
not be useful with the standard emacs outline package.

I have yet to go through and extract from the library manual, at least
to consolidate some of the standard-language facts (eg, built-in
exceptions, etc). On quick perusal, it looks like there is a lot of
important elaboration there. I may get to it sometime soon, at least
to consolidate some of the elaborations on the ref manual stuff. In
the meanwhile, suggestions and corrections for refining this version
are welcome. (I don't guarantee actually doing anything with them,
however, but hope to have a bit more time to clean up my notes...)

ken.manheimer@nist.gov, 301 975-3539

A Python Bestiary
Itemizing Python Objects and Nuances

ChangeLog ($Date: 1994/06/15 23:12:39 $ $Revision: 1.2 $ $Author: klm $)

Notable lexical entities

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

String Literal Escapes

\newline Ignored (escape newline)
\\ Backslash (\) \e Escape (ESC) \v Vertical Tab (VT)
\' Single quote (') \f Formfeed (FF) \oOO char with
\" Double quote (") \n Linefeed (LF) octal value OO
\a Bell (BEL) \r Carriage Return (CR) \xXX char with
\b Backspace (BS) \t Horizontal Tab (TAB) hex value XX

Illegitimate Tokens (only valid in strings): @ $ " ?

Objects - behaviors, special attributes, operations, statements, etc

. > All types

id(x) - unique identifier for object (currently, its address)
object instantiation: __init__(self, args)
object demise: __del__(self)
repr() and `...` conversions: __repr__(self)
str() and 'print' statement: __str__(self)
< == > <= <> != >=, is [not], [not] in: __cmp__(self)
hash() and dictionary operations: __hash__(self):

. } Boolean values

false values are: None, numeric zeros, empty sequences and mappings
true values are: all other values
operators: 'not', 'and', 'or'; binary ones shortstop

. < General Name Space behavior and binding

. } Name space search order: local, global, builtin

. } Code Block scopes (ns = name space, cb = containing block)

Code block type Global ns Local ns Notes
--------------- --------- -------- -----
Module module ns same as global ns
Script __main__ ns same as global ns
Interactive cmd __main__ ns same as global ns
Class def global ns of cb new ns
Function body global ns of cb new ns
'exec' string global ns of cb local ns of cb (or args)
'eval' string global ns of caller local ns of caller (or args)
'execfile' file global ns of caller local ns of caller (or args)
'input' expr global ns of caller local ns of caller

. = Binding operations:

. ~ SyntaxError on attempt to bind to literals or other non-bindables
. ~ NameError: on attempt to evaluate unbound atom

. } assignment statement: targ1, targ2, ,,, = obj1, obj2, ,,,
. } deletion statement: del obj1, obj2, ...
. } target identifiers of for loops, except clauses
. } formal params
. } import statement: # Instantiate ns/ns components within another
. } class and func defs

. } Name space linkage

global statement: global id, ... # Interpret id's as globals
. X access statement: access ... # control inst and class vars access

. > Numbers

. } Types

Integers: -2^31 to 2^31 - 1; OverFlow error if bounds exceeded
Long Integers: unlimited - '2147483648L'
Floating point: machine double-precision floating point - '2147483648.0'

. } Numeric operations vs special methods (s = self, o = other)

s+o = __add__(s,o) s-o = __sub__(s,o)
s*o = __mul__(s,o) s/o = __div__(s,o)
s%o = __mod__(s,o) divmod(s,o) = __divmod__(s,o)
pow(s,o) = __pow__(s,o)
s&o = __and__(s,o)
s^o = __xor__(s,o) s|o = __xor__(s,o)
s<<o = __lshift__(s,o) s<<o = __rshift__(s,o)
nonzero(s) = __nonzero__(s) coerce(s,o) = __coerce__(s,o)
-s = __neg__(s) +s = __pos__(s)
abs(s) = __abs__(s) ~s = __invert__(s)
int(s) = __int__(s) long(s) = __long__(s)
float(s) = __float__(s)
oct(s) = __oct__(s) hex(s) = __hex__(s)

. } Numeric exceptions

. ~ TypeError: raised on application of arithemetic opertion to non-number
. ~ OverflowError: numeric bounds exceeded

. > Sequences

. } Strings (immutable): "string contents"

'this is a string'
"and so is this"
""" and this begins a "multi-line" string with embedded quotes...
... and this is the end of that string."""
`...` converts arbitrary expr to string (according to __repr__/repr())
chr() and ord() convert from string to int and vice versa

. } Tuples (immutable): (oneelem, another, etc)

parens may be left off all but empty tuples
represent singletons by affixing a comma to an expr
represent empty tuple using empty parens
. = assignment - target tuple items must be 1-1 with object tuple items

. } Lists (mutable): [oneelem, another, etc]

. = assignment - target list items must be 1-1 with object list items
subscription must yield int index of existing element, 2b assigned
Negative subscript first has len added before index interpretation
. ~ IndexError rasied if index doesn't point to existing element
. = deletion - similar rules as for assignment

. } Sequences special methods - Mappings' special methods (see below), plus:

. ( Notes for __*slice__ operations:
Missing i replaced by 0, j replaced by len(self).
len(self) is automatically added to negative i or j)

__getslice__(self, i, j): implements self[i:j])
__setslice__(self, i, j): implements assignement to self[i:j]
__delslice__(self, i, j): implements deletion of self[i:j]

. > Mappings

. } Dictionaries (mutable): {key1: 'val1', key2: 'val2', ...}
keys can be of any immutable types

. } Mappings and sequences special methods

__len__(self): len() built-in and boolean evaluation
length of object, >= 0; obj with len 0 = false if not __cmp__ defined

. ( Note for __*item__ operations:
len(self) is *not* automatically added to negative i or j,
in contrast to mechanism for sequence slices. Behavior
must be explicitly implemented if desired.)

__getitem__(self, key): implements evaluation of self[key]
__setitem__(self, key): implements evaluation assignment to self[key]
__delitem__(self, key): implements evaluation deletion to self[key]

. = assignment -

Subscript changes existing or creates new key/value pair
. ~ TypeError is raised if key is not mappable
subscr types may vary (contrary to ref man description of assignments)

. > Callables

. } User defined functions:

func_code: code object representing compiled function body
func_globals: ref to dict of globals of funcs definition module

. } User defined methods - special attrs:

im_self: class instance object
im_func: function object

. } Classes

container for dictionary containing class's ns dictionary
__dict__: ro attr, class ns as dictionary object
__bases__: ro attr, class' base classes in tuple
__init__(self, args..): implements object instantiation
__del__(self): implements impending object deletion
__repr__(self): implements repr() built-in and `...` conversions
__str__(self): implements str() built-in and print statement
__cmp__(self, other): comparisons: > == > <= <> != >= is [not], [not] in
__hash__(self): implements hash() built-in and dictionary operations

. } Class instances

__dict__: ro attr, class' attribute dictionary
__class__: ro attr, instance's class object

. > Modules

functions and methods in a module share module's "global" namespace
function uses "global" statement to instantiate var in global context
Modules use "import" to incorp other module's names - see Name Spaces, ^
__dict__: ro attr, module's ns as dictionary object
__name__: ro attr, module's name as string

. > Files

wrapper around a C stdio file pointer
open() creates (also, posix.popen(), and socket objects makefile)
sys.stdin, sys.stdout, sys.stderr are standard io-stream file objects

. > Internal types

. } Code objects - represent exectuable code - function obj sans context
. } Frame objects - represent executable frames - may occur in traceback objs
. } Traceback objects - stack trace of an exception

Control statements

. > Calls

. } return: return [expr] # Leave current func call with expr value
. } function def: def name (param-list): suite
. } class def: class name [(inheritance)]: suite

. > Conditionals and Loops

. } break: break # Terminate nearest enclosing loop
. } continue: continue # Continue next cycle of enclosing loop
. } if: if cond: suite \n [elif cond: suite \n ...] \n [else: suite]
. } for: for targs in conds: suite \n [ else: suite ]
. } while: while cond: suite \n else: suite

. > Evaluation

. } exec: exec expr [ in expr2 [, expr3]] # Dynamic execution of python code
. } there is also a built-in 'eval' function, for expressions

. > Exceptions

. } raise: raise expr [, expr2] # Raise exception expr, passing expr2 if any
. } try: two forms:

Other statements

. > print: cond1, cond2, etc # Write values to stdout