Revised "cheat sheet"

Kenneth Manheimer (klm@nist.gov)
Fri, 17 Jun 1994 15:39:49 GMT

I've incorporated some corrections and suggestions from the newsgroup
to my "cheat sheet", reconciled the structure a lot, and filled in a
lot of missing pieces.

Again, in case it would be useful to others, ...

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

[P.S. Does anyone notice, have strong impressions, about whether it
would be more readable with less or more bullet chars? (Ie, the '.
>' stuff.) Also, drop me a line if you would like to keep up with
revisions of this. If only a few reply, i can use email, rather
than occupy the newsgroup...]

A Python Bestiary
Itemizing Python Objects and Nuances
In Allout outline format

ChangeLog ($Date: 1994/06/17 15:23:45 $ $Revision: 1.3 $ $Author: klm $)

Notable lexical entities
========================

Keywords

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
====================================================================

[ General Environment

} Boolean values and operators

= False values: None, numeric zeros, empty sequences and mappings
= True values: all other values

> not X: if X is false then 1, else 0
( 'or', 'not' evaluate second arg only if necessary to determine outcome)
> X or Y: if X is false then Y, else X
> X and Y: if X is false then X, else Y

} Special methods for any type (s: self)

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

} Special informative state attributes for some types:

= X.__dict__ dict used to store object's writeable attributes
= X.__methods__ list of X's methods; on many built-in types.
= X.__members__ lists of X's data attributes
= X.__class__ class to which X belongs
= X.__bases__ tuple of X base classes

} General Name Space behavior and binding

} Name space search order: local, global, builtin

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

= Binding operations and exception:

} Name space linkage

[ Numbers

@ Integers: 'C' long, >= 32 bits precision; OverflowError if bounds exceeded
@ Long Integers: unlimited precision - '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) (bitwise)
> int(s) = __int__(s) long(s) = __long__(s)
> float(s) = __float__(s)
> oct(s) = __oct__(s) hex(s) = __hex__(s)

} Numeric functions:
> range(start, end, step) create list of arithmetic progressions
> round(x, n=0) round floating point x to n decimal places
> xrange(start, end, step) create virtual list of arithmetic progressions

} Numeric exceptions

~ TypeError: raised on application of arithemetic opertion to non-number
~ OverflowError: numeric bounds exceeded
~ ZeroDivisionError: raised when zero second argument of div or modulo op

[ Collections - Sequences and Mappings

} All Collections general operations vs methods (s: self, i: index or key)

> len(s) = __len__(s) length of object, >= 0. Length 0 == false
> s[i] = __getitem__(s,i) Element at index/key i, origin 0

> Sequences

@ String (immutable sequences): "string contents"

'this is a string'
"and so is this"
""" and this begins a "multi-line" string with embedded quotes,
and this ends it."""

> `objs...` = __repr__(objs...), converts arbitrary expr to string
> chr(string) convert from string to int
> ord(int) convert from int to string
> string % arg format operator, a la C sprintf

@ Tuples (immutable sequences): (oneelem, another, etc)

parens may be left off all but empty tuples
singletons represented by affixing a comma to an expr
empty tuple represented using empty parens

@ Lists (mutable sequences): [oneelem, another, etc]

= assignment - must be 1-1 map of items in target and object sequences
= deletion - similar rules as for assignment

} Sequences general ops vs methods (s: self, i,j: indices, v: val)

all collections general methods, plus:
> s[i:j] = __getslice__(s,i,j) Elements with index k s.t. i <= k < j
> min(s) smallest item of s
> max(s) largest item of s
> v [not] in s 1 if v [not] equal to an item in s, else 0
> s + seq concatenation of s and seq
> s * num num copies of s concatenated, also, `num * s'

} Immutable sequence ops vs methods (s: self, i,j: indices, v: val)

all collections general methods, plus:
All sequences' general methods, plus
> s[i:j] = __getslice__(s,i,j) Elements with index k s.t. i <= k < j
( For s[i:j], len(self) is intrinsically added to i, j < 0)
( Complex elements of immutable sequences may themselves be mutable.)

} Mutable sequence ops vs methods (s: self, i,j: indices, v: val)

All sequences' general methods, plus:
( for non-slice refs, i < 0 intrinsically has len(s) added)
( For slice refs, len(s) *is not* intrinsically added to i, j < 0)
( for assignment/deletion, index refs must point to existing items
> s[i]=v = __setitem__(s,i,v)
> del s[i] = __delitem__(s,i)
> s[i:j] = __getslice__(s,i,j)
> s[i:j]=seq = __setslice__(s,i,j,seq)
> del s[i:j] = __delslice__(s,i,j) == s[i:j] = []
> s.append(seq) == `s[len(seq):len(seq)] = [seq]'
> s.count(v) number of i's for which `s[i] == v'
> s.index(v) first i such that `s[i] == v', or IndexError if none
> s.insert(i, v) == `s[i:i] = [v]'
> s.remove(v) == `del s[s.index(v)]', or IndexError if v not in s
> s.reverse() reverse the items of s in place
> s.sort() permute s items so s[i] <= s[j], for i < j

> Mappings

@ Dictionaries: {key1: val1, key2: val2, ...}

built-in types as keys must be unalterable: obj & all contents immutable
User-defined classes as keys must have __hash__() and __cmp__() methods
~ TypeError is raised if key not acceptable
~ KeyError is raised if reference made using non-existent key
key types may vary (contrary to ref man)

} Dictionaries ops vs methods (s: self, k: key, v: val)

> all collections general ops, plus:
> hash(s) = __hash__(s) - hash value for dictionary references
> s[k]=v = __setitem__(s,k,v)
> del s[k] = __delitem__(s,k)
> s.items() = a list copy of s's (key, item) pairs
> s.keys() = a list copy of s's keys
> s.values() = a list copy of s's values
> s.has_keys(k) = 1 if s has key k, else 0
( s.items, .keys, and .values yield random but mutually consistent order)

[ Callables

@ User defined functions: 'def name (param-list): suite'
suite is not evaluated at statement execution, but at function invocation
function parameters, comma separated on param-list:
= func_code: special attr, code object representing compiled function body
= func_globals: special attr, ref to global dict of funcs definition module
> func(arg-list) invocation

@ User defined methods: like functions, with extra implicit arg
Same as functions, but passed class instance as additional first argument
= im_self: special attr, method's class instance object
= im_func: special attr, function object
> mthd(args) invocation, same as mthd.im_func(mthd.im_self, args)

@ Classes: 'class name [(inheritance)]: suite'
inheritance list is evaluated, if any, to identify base classes for name
suite is executed in new local name space, which goes to the class object
class name is bound in encompassing local name space
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

@ Class instances

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

} Callables special method vs ops (f: function)
> apply(f, args-tuple) call f with args-tuple as arg list
> compile(str, flnm, kind) compile string into exectuable code object
> eval(str, glbls=, lcls=) evaluate string as expression (cond_list)
> filter(f, seq) => seq of seq elems for which f is true
> map(f, lst, [lst2, ...]) => list of f applied to succesive lsts elems
> reduce(f, lst, initlzr) => value of f applied to elems and cume result

@ Null object: None

@ Type objects: <type 'int'>
> accessed via built-in func 'type()'
( equal only when identical (same id()),
so can't just use the string name, must use object with the same str val)

@ 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

} Special attrs, methods, and operations
__dict__: attr, module's ns as dictionary; can modify vals but not sruct
__name__: ro attr, module's name as string
> import Instantiate module, module components, within another
> reload Reread an imported module

@ Files

wrapper around a C stdio file pointer
sys.stdin, sys.stdout, sys.stderr are standard io-stream file objects

} File operations:
> open(nm, mode='r', bufsize=sysdef) return new file object
> close() A closed file cannot be read or written anymore.
> flush() Flush the internal buffer, like `stdio''s `fflush()'.
> isatty() 1 if the file is connected to a tty(-like) device, else 0.
> read(SIZE) Read up to SIZE bytes from the file, less if EOF or no data
> readline() Read one entire line from the file.
> readlines() `readline()' til EOF and return list of lines read.
> seek(OFFSET,WHENCE) Set file's current position, like `stdio's `fseek()'
> tell() Return the file's current position, like `stdio''s `ftell()'.
> write(STR) Write a string to the file. There is no return value.

} File functions:
> input(prompt='') like raw input but accept '\' line continuations
> print exp, exp2, ... Write values to stdout
> raw_input(prompt='') prompt then read single line of input

[ 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 and Evaluation
( See also Callables, in Objects section above, for ops and methods.)

> exec: exec expr [ in expr2 [, expr3]] # Dynamic execution of python code
> return: return [expr] # Leave current func call with expr value

[ Conditionals and Loops
( See also Boolean values, in General Environment section of Objects, above)

> 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

[ Exceptions

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

} Workspace exploration and idiom hints

> dir() get object keys, defaults to local name space
> X.__methods__ list of methods supported by X (if any)
> X.__members__ List of X's data attributes
> if __name__ == '__main__': main() invoke main if running as script
> map(None, lst1, lst2, ...) merge lists
> b = a[:] create copy of seq structure