NB: features added in 2.0 since 1.5.2 are colored dark magenta.
Based on:
Python Bestiary, Author: Ken Manheimer,
ken.manheimer@nist.gov
Python manuals, Authors: Guido van Rossum and Fred
Drake
What's new in Python 2.0, Authors: A.M. Kuchling and Moshe Zadka
python-mode.el, Author: Tim Peters,
tim_one@email.msn.com
and the readers of comp.lang.python
Python's nest: http://www.python.org
Developement: http://python.sourceforge.net/
ActivePython : http://www.ActiveState.com/ASPN/Python/
newsgroup: comp.lang.python
Help desk: help@python.org
Resources: http://starship.python.net/
and http://www.vex.net/parnassus/
Full documentation: http://www.python.org/doc/
An excellent Python reference book: Python
Essential Reference by David Beazley (New Riders)
| python [-diOStuUvxX?] [-c command | script | - ] [args] |
| Option | Effect |
|---|---|
| -d | Outputs parser debugging information (also PYTHONDEBUG=x) |
| -i | Inspect interactively after running script (also PYTHONINSPECT=x) and force prompts, even if stdin appears not to be a terminal |
| -O | Optimize generated bytecode (set __debug__ = 0 =>s suppresses asserts) |
| -S | Don't perform 'import site' on initialization |
| -t | Issue warnings about inconsistent tab usage (-tt: issue errors) |
| -u | Unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x). |
| -U | Force Python to interpret all string literals as Unicode literals. |
| -v | Verbose (trace import statements) (also PYTHONVERBOSE=x) |
| -x | Skip first line of source, allowing use of non-unix Forms of #!cmd |
|
|
|
| -? | Help! |
| -c command | Specify the command to execute (see next section). This terminates the option list (following options are passed as arguments to the command). |
| script |
the name of a python file (.py) to execute read from stdin. Anything afterward is passed as options to python script or command, not interpreted as an option to interpreter itself. |
| args | passed to script or command (in sys.argv[1:]) |
| If no script or command, Python enters interactive mode. |
| Variable | Effect |
|---|---|
| PYTHONHOME | Alternate prefix directory (or prefix;exec_prefix). The default module search path uses prefix/lib |
| PYTHONPATH | Augments the default search path for module files. The format is the same as the shell's $PATH: one or
more directory pathnames separated by ':' or ';' without spaces around (semi-)colons! On Windows first search for Registry key HKEY_LOCAL_MACHINE\Software\Python\PythonCore\x.y\PythonPath (default value). You may also define a key named after your application with a default string value giving the root directory path of your app. |
| PYTHONSTARTUP | If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode (no default). |
| PYTHONDEBUG | If non-empty, same as -d option |
| PYTHONINSPECT | If non-empty, same as -i option |
| PYTHONSUPPRESS | If non-empty, same as -s option |
| PYTHONUNBUFFERED | If non-empty, same as -u option |
| PYTHONVERBOSE | If non-empty, same as -v option |
| PYTHONCASEOK | If non-empty, ignore case in file/module names (imports) |
and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass def finally in print
"a string enclosed by double quotes"
'another string delimited by single quotes and with a " inside'
'''a string containing embedded newlines and quote (') marks, can be delimited with triple quotes.'''
""" may also use 3- double quotes as delimiters """
u'a unicode string' U"Another unicode string"
r'a raw string where \ are kept (literalized): handy for regular expressions and windows paths!'
R"another raw string" -- raw strings cannot end with a \
ur'a unicode raw string' UR"another raw unicode"Use \ at end of line to continue a string on next line. adjacent strings are concatened, e.g. 'Monty' ' Python' is the same as 'Monty Python'. u'hello' + ' world' --> u'hello world' (coerced to unicode) String Literal Escapes
\newline Ignored (escape newline)
\\ Backslash (\) \e Escape (ESC) \v Vertical Tab (VT)
\' Single quote (') \f Formfeed (FF) \OOO char with octal value OOO
\" Double quote (") \n Linefeed (LF)
\a Bell (BEL) \r Carriage Return (CR) \xHH char with hex value HH
\b Backspace (BS) \t Horizontal Tab (TAB)
\uHHHH unicode char with hex value HHHH, can only be used in unicode string
\UHHHHHHHH unicode char with hex value HHHHHHHH, can only be used in unicode string
\AnyOtherChar is left as-is
Decimal integer: 1234, 1234567890546378940L (or l) Octal integer: 0177, 0177777777777777777L (begin with a 0) Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFFL (begin with 0x or 0X) Long integer (unlimited precision): 1234567890123456L (ends with L or l) Float (double precision): 3.14e-10, .001, 10., 1E3 Complex: 1J, 2+3J, 4+5j (ends with J or j, + separates (float) real and imaginary parts)
Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to '0'; End defaults to 'sequence-length'.
Dictionary of length 0, 1, 2, etc:
{} {1 : 'first'} {1 : 'first', 'next': 'second'}
| Highest | Operator | Comment |
|---|---|---|
| , [...] {...} `...` | Tuple, list & dict. creation; string conv. | |
| s[i] s[i:j] s.attr f(...) | indexing & slicing; attributes, fct calls | |
| +x, -x, ~x | Unary operators | |
| x**y | Power | |
| x*y x/y x%y | mult, division, modulo | |
| x+y x-y | addition, substraction | |
| x<<y x>>y | Bit shifting | |
| x&y | Bitwise and | |
| x^y | Bitwise exclusive or | |
| x|y | Bitwise or | |
| x<y x<=y x>y x>=y
x==y x!=y x<>y
x is y x is not y x in s x not in s |
Comparison,
identity, membership |
|
| not x | boolean negation | |
| x and y | boolean and | |
| x or y | boolean or | |
| Lowest | lambda args: expr | anonymous function |
| Comparison | Meaning | Notes |
|---|---|---|
| < | strictly less than |
|
| <= | less than or equal to | |
| > | strictly greater than | |
| >= | greater than or equal to | |
| == | equal to | |
| != or <> | not equal to | |
| is | object identity |
|
| is not | negated object identity |
|
| Value or Operator | Returns | Notes |
|---|---|---|
| None, numeric zeros, empty sequences and mappings | False | |
| all other values | True | |
| not x | True if x is False, else True | |
| x or y | if x is False then y, else x |
|
| x and y | if x is False then x, else y |
|
None is used as default return value on functions. Built-in single object with type NoneType.
Input that evaluates to None does not print when running Python interactively.
Floats are implemented with C doubles.
Integers are implemented with C longs.
Long integers have unlimited size (only limit is system resources)
| Operation | Result |
|---|---|
| abs(x) | the absolute value of x |
| int(x) | x converted to integer |
| long(x) | x converted to long integer |
| float(x) | x converted to floating point |
| -x | x negated |
| +x | x unchanged |
| x + y | the sum of x and y |
| x - y | difference of x and y |
| x * y | product of x and y |
| x / y | quotient of x and y |
| x % y | remainder of x / y |
| divmod(x, y) | the tuple (x/y, x%y) |
| x ** y | x to the power y (the same as pow(x, y)) |
| Operation | >Result |
|---|---|
| ~x | the bits of x inverted |
| x ^ y | bitwise exclusive or of x and y |
| x & y | bitwise and of x and y |
| x | y | bitwise or of x and y |
| x << n | x shifted left by n bits |
| x >> n | x shifted right by n bits |
| Operation | Result | Notes |
|---|---|---|
| x in s | 1 if an item of s is equal to x, else 0 | |
| x not in s | 0 if an item of s is equal to x, else 1 |
|
| s + t | the concatenation of s and t | |
| s * n, n*s | n copies of s concatenated |
|
| s[i] | i'th item of s, origin 0 |
|
| s[i:j] | slice of s from i (included) to j (excluded) |
|
| len(s) | length of s | |
| min(s) | smallest item of s |
|
| max(s) | largest item of (s) |
|
Notes :(1) if i or j is negative, the index is relative to the end of the string, ie len(s)+ i or len(s)+j is
| Operation | Result | Notes |
|---|---|---|
| s[i] =x | item i of s is replaced by x | |
| s[i:j] = t | slice of s from i to j is replaced by t |
|
| del s[i:j] | same as s[i:j] = [] | |
| s.append(x) | same as s[len(s) : len(s)] = [x] |
|
| s.extend(x) | same as s[len(s):len(s)]= x | |
| s.count(x) | return number of i's for which s[i] == x | |
| s.index(x) | return smallest i such that s[i] == x |
|
| s.insert(i, x) | same as s[i:i] = [x] if i >= 0 | |
| s.remove(x) | same as del s[s.index(x)] |
|
| s.pop([i]) | same as x = s[i]; del s[i]; return x | |
| s.reverse() | reverse the items of s in place |
|
| s.sort([cmpFct]) | sort the items of s in place |
|
Notes :
(1) raise a ValueError exception when
x
is not found in s (i.e. out of range).
(2) The sort() method takes
an optional argument specifying a comparison fct of 2 arguments (list items)
which should
return -1, 0, or 1 depending on whether the 1st argument is considered
smaller than, equal to, or larger than the 2nd
argument. Note that this slows the sorting process down considerably.
(3) The sort() and reverse()
methods modify the list in place for economy of space when
sorting or reversing a large list.
They don't return the sorted or reversed list to remind you of this side
effect.
(4) The pop()
method is not supported by mutable sequence types
other than lists.
The optional argument i defaults to -1, so that by default the last
item is removed and returned.
(5) Raises an exception when x is not a list object.
| Operation | Result | Notes |
|---|---|---|
| len(d) | the number of items in d | |
| d[k] | the item of d with key k |
|
| d[k] = x | set d[k] to x | |
| del d[k] | remove d[k] from d |
|
| d.clear() | remove all items from d | |
| d.copy() | a shallow copy of d | |
| d.has_key(k) | 1 if d has key k, else 0 | |
| d.items() | a copy of d's list of (key, item) pairs |
|
| d.keys() | a copy of d's list of keys |
|
| d1.update(d2) | for k, v in d2.items(): d1[k] = v |
|
| d.values() | a copy of d's list of values |
|
| d.get(k,defaultval) | the item of d with key k |
|
| d.setdefault(k,defaultval) | the item of d with key k |
|
Notes :
TypeError is raised if key is not acceptable
(1) KeyError is raised if key k is not in the map
(2) Keys and values are listed in random order
(3) d2 must be of the same type as d1
(4) Never raises an exception if k is not in the map, instead it returns defaultVal. defaultVal is optional, when not provided and k is not in the map, None is returned.
(5) Never raises an exception if k is not in the map, instead it returns defaultVal, and adds k to map with value defaultVal. defaultVal is optional. When not provided and k is not in the map, None is returned and added to map.
| Operation | Result | Notes |
|---|---|---|
| s.capitalize() | return a copy of s with only its first character capitalized. |
|
| s.center(width) | return a copy of s centered in a string of length width. |
|
| s.count(sub[,start[,end]]) | return the number of occurrences of substring sub in string s. |
|
| s.encode([encoding[,errors]]) | return an encoded version of s. Default encoding is the current default string encoding. |
|
| s.endswith(suffix[,start[,end]]) | return true if s ends with the specified suffix, otherwise return false. |
|
| s.expandtabs([tabsize]) | return a copy of s where all tab characters are expanded using spaces. |
|
| s.find(sub[,start[,end]]) | return the lowest index in s where substring sub is found. Return -1 if sub is not found. |
|
| s.index(sub[,start[,end]]) | like find(), but raise ValueError when the substring is not found. |
|
| s.isalnum() | return true if all characters in s are alphanumeric, false otherwise. |
|
| s.isalpha() | return true if all characters in s are alphabetic, false otherwise. |
|
| s.isdigit() | return true if all characters in s are digit characters, false otherwise. |
|
| s.islower() | return true if all characters in s are lowercase, false otherwise. |
|
| s.isspace() | return true if all characters in s are whitespace characters, false otherwise. |
|
| s.istitle() | return true if string s is a titlecased string, false otherwise. |
|
| s.isupper() | return true if all characters in s are uppercase, false otherwise. |
|
| s.join(seq) | return a concatenation of the strings in the sequence seq, seperated by 's's. |
|
| s.ljust(width) | return s left justified in a string of length width. |
|
| s.lower() | return a copy of s converted to lowercase. |
|
| s.lstrip() | return a copy of s with leading whitespace removed. |
|
| s.replace(old, new[, maxsplit]) | return a copy of s with all occurrences of substring old replaced by new. |
|
| s.rfind(sub[,start[,end]]) | return the highest index in s where substring sub is found. Return -1 if sub is not found. |
|
| s.rindex(sub[,start[,end]]) | like rfind(), but raise ValueError when the substring is not found. |
|
| s.rjust(width) | return s right justified in a string of length width. |
|
| s.rstrip() | return a copy of s with trailing whitespace removed. |
|
| s.split([sep[,maxsplit]]) | return a list of the words in s, using sep as the delimiter string. |
|
| s.splitlines([keepends]) | return a list of the lines in s, breaking at line boundaries. |
|
| s.startswith(prefix[,start[,end]]) | return true if s starts with the specified prefix, otherwise return false. |
|
| s.strip() | return a copy of s with leading and trailing whitespace removed. |
|
| s.swapcase() | return a copy of s with uppercase characters converted to lowercase and vice versa. |
|
| s.title() | return a titlecased copy of s, i.e. words start with uppercase characters, all remaining cased characters are lowercase. |
|
| s.translate(table[,deletechars]) | return a copy of s mapped through translation table table. |
|
| s.upper() | return a copy of s converted to uppercase. |
|
Notes :
(1) Padding is done using spaces.
(2) If optional argument start
is supplied, substring s[start:] is processed.
If optional arguments start and end are supplied, substring
s[start:end] is processed.
(3) Optional argument errors
may be given to set a different error handling scheme. The default for
errors is 'strict', meaning that encoding errors raise a
ValueError. Other possible values are 'ignore' and 'replace'.
(4) If optional argument tabsize
is not given, a tab size of 8 characters is assumed.
(5) Returns false if string s
does not contain at least one character.
(6) Returns false if string s
does not contain at least one cased character.
(7) A titlecased string is a string
in which uppercase characters may only follow uncased characters and lowercase
characters only cased ones.
(8) s is returned if width
is less than len(s).
(9) If the optional argument maxsplit
is given, only the first maxsplit occurrences are replaced.
(10) If sep is not specified
or None, any whitespace string is a separator. If maxsplit
is given, at most maxsplit splits are done.
(11) Line breaks are not included
in the resulting list unless keepends is given and true.
(12) table must be a string
of length 256. All characters occurring in the optional argument deletechars
are removed prior to translation.
| formatString % args--> evaluates to a string |
'%s has %03d quote types.' % ('Python', 2) # => 'Python has 002 quote types.'
a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python}
(vars() function very handy to use on right-hand-side.)
| Conversion | Meaning |
|---|---|
| d | Signed integer decimal. |
| i | Signed integer decimal. |
| o | Unsigned octal. |
| u | Unsigned decimal. |
| x | Unsigned hexidecimal (lowercase). |
| X | Unsigned hexidecimal (uppercase). |
| e | Floating point exponential format (lowercase). |
| E | Floating point exponential format (uppercase). |
| f | Floating point decimal format. |
| F | Floating point decimal format. |
| g | Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise. |
| G | Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise. |
| c | Single character (accepts integer or single character string). |
| r | String (converts any python object using repr()). |
| s | String (converts any python object using str()). |
| % | No argument is converted, results in a "%" character in the result. (The complete specification is %%.) |
| Flag | Meaning |
|---|---|
| # | The value conversion will use the ``alternate form''. |
| 0 | The conversion will be zero padded. |
| - | The converted value is left adjusted (overrides "-"). |
| (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. | |
| + | A sign character ("+" or "-") will precede the conversion (overrides a "space" flag). |
| Operation | Result |
|---|---|
| f.close() | Close file f. |
| f.fileno() | Get fileno (fd) for file f. |
| f.flush() | Flush file f's internal buffer. |
| f.isatty() | 1 if file f is connected to a tty-like dev, else 0. |
| f.read([size]) | Read at most size bytes from file f and return as a string object. If size omitted, read to EOF. |
| f.readline() | Read one entire line from file f. |
| f.readlines() | Read until EOF with readline() and return list of lines read. |
| f.seek(offset[, whence=0]) |
Set file f's position, like "stdio's fseek()".
whence == 0 then use absolute indexing. whence == 1 then offset relative to current pos. whence == 2 then offset relative to file end. |
| f.tell() | Return file f's current position (byte offset). |
| f.write(str) | Write string to file f. |
| f.writelines(list) | Write list of strings to file f. |
pass -- Null statement del name[,name]* -- Unbind name(s) from object. Object will be indirectly (and automatically) deleted only if no longer referenced. print [>> fileobject,] [s1 [, s2 ]* [,] -- Writes to sys.stdout, or to fileobject if supplied. Puts spaces between arguments. Puts newline at end unless statement ends with comma. Print is not required when running interactively, simply typing an expression will print its value, unless the value is None. exec x [in globals [,locals]] -- Executes x in namespaces provided. Defaults to current namespaces. x can be a string, file object or a function object. callable(value,... [id=value], [*args], [**kw]) -- Call function callable with parameters. Parameters can be passed by name or be omitted if function defines default values. E.g. if callable is defined as "def callable(p1=1, p2=2)" "callable()" <=> "callable(1, 2)" "callable(10)" <=> "callable(10, 2)" "callable(p2=99)" <=> "callable(1, 99)" *args is a tuple of positional arguments. **kw is a dictionary of keyword arguments.
| Operator | Result | Notes |
|---|---|---|
| a = b | Basic assignment - assign object b to label a |
|
| a += b | Roughly equivalent to a = a + b |
|
| a -= b | Roughly equivalent to a = a - b |
|
| a *= b | Roughly equivalent to a = a * b |
|
| a /= b | Roughly equivalent to a = a / b |
|
| a %= b | Roughly equivalent to a = a % b |
|
| a **= b | Roughly equivalent to a = a ** b |
|
| a &= b | Roughly equivalent to a = a & b |
|
| a |= b | Roughly equivalent to a = a | b |
|
| a ^= b | Roughly equivalent to a = a ^ b |
|
| a >>= b | Roughly equivalent to a = a >> b |
|
| a <<= b | Roughly equivalent to a = a << b |
|
if condition: suite [elif condition: suite]* [else: suite] -- usual if/else_if/else statement while condition: suite [else: suite] -- usual while statement. "else" suite is executed after loop exits, unless the loop is exited with "break" for element in sequence: suite [else: suite] -- iterates over sequence, assigning each element to element. Use built-in range function to iterate a number of times. "else" suite executed at end unless loop exited with "break" break -- immediately exits "for" or "while" loop continue -- immediately does next iteration of "for" or "while" loop return [result] -- Exits from function (or method) and returns result (use a tuple to return more than one value). If no result given, then returns None.
assert expr[, message] -- expr is evaluated. if false, raises exception AssertionError with message. Inhibited if __debug__ is 0.
try: suite1 [except [exception [, value]: suite2]+ [else: suite3] -- statements in suite1 are executed. If an exception occurs, look in "except" clauses for matching <exception>. If matches or bare "except" execute suite of that clause. If no exception happens suite in "else" clause is executed after suite1. If exception has a value, it is put in value. exception can also be tuple of exceptions, e.g. "except (KeyError, NameError), val: print val" try: suite1 finally: suite2 -- statements in suite1 are executed. If no exception, execute suite2 (even if suite1 is exited with a "return", "break" or "continue" statement). If exception did occur, executes suite2 and then immediately reraises exception. raise exception [,value [, traceback]] -- raises exception with optional value value. Arg traceback specifies a traceback object to use when printing the exception's backtrace. raise -- a raise statement without arguments re-raises the last exception raised in the current function
my_exception = 'You did something wrong'
try:
if bad:
raise my_exception, bad
except
my_exception, value:
print 'Oops', value
class text_exception(Exception): pass try: if bad: raise text_exception() # This is a shorthand for the form # "raise <class>, <instance>" except Exception: print 'Oops' # This will be printed because # text_exception is a subclass of Exception When an error message is printed for an unhandled exception which is a class, the class name is printed, then a colon and a space, and finally the instance converted to a string using the built-in function str().
All built-in exception classes derives from StandardError, itself derived from Exception.
Packages (>1.5): a package is a name space which maps to a directory including module(s) and the special initialization module '__init__.py' (possibly empty). Packages/dirs can be nested. You address a module's symbol via '[package.[package...]module.symbol's.
import module1 [as name1] [, module2]* -- imports modules. Members of module must be referred to by qualifying with [package.]module name: "import sys; print sys.argv:" "import package1.subpackage.module; package1.subpackage.module.foo()" module1 renamed as name1, if supplied. from module import name1 [as othername1] [, name2]* -- imports names from module module in current namespace. "from sys import argv; print argv" "from package1 import module; module.foo()" "from package1.module import foo; foo()" name1 renamed as othername1, if supplied. from module import * -- imports all names in module, except those starting with "_"; *to be used sparsely, beware of name clashes* : "from sys import *; print argv" "from package.module import *; print x' NB: "from package import *" only imports the symbols defined in the package's __init__.py file, not those in the template modules! global name1 [, name2]* -- names are from global scope (usually meaning from module) rather than local (usually meaning only in function). -- E.g. in fct without "global" statements, assuming "a" is name that hasn't been used in fct or module so far: -Try to read from "a" -> NameError -Try to write to "a" -> creates "a" local to function -If "a" not defined in fct, but is in module, then -Try to read from "a", gets value from module -Try to write to "a", creates "a" local to fct But note "a[0]=3" starts with search for "a", will use to global "a" if no local "a".
def func_id ([param_list]): suite -- Creates a function object & binds it to name func_id.
param_list ::= [id [, id]*] id ::= value | id = value | *id | **id[Args are passed by value.Thus only args representing a mutable object can be modified (are inout parameters). Use a tuple to return more than one value]
Example: def test (p1, p2 = 1+1, *rest, **keywords): -- Parameters with "=" have default value (v is evaluated when function defined). If list has "*id" then id is assigned a tuple of all remaining args passed to function (like C vararg) If list has "**id" then id is assigned a dictionary of all extra arguments passed as keywords.
class <class_id> [(<super_class1> [,<super_class2>]*)]: <suite>
-- Creates a class object and assigns it name <class_id>
<suite> may contain local "defs" of class methods and
assignments to class attributes.
Example:
class my_class (class1, class_list[3]): ...
Creates a class object inheriting from both "class1" and whatever
class object "class_list[3]" evaluates to. Assigns new
class object to name "my_class".
- First arg to class methods is always instance object, called 'self'
by convention.
- Special method __init__() is called when instance is created.
- Special method __del__() called when no more reference to object.
- Create instance by "calling" class object, possibly with arg
(thus instance=apply(aClassObject, args...) creates an instance!)
- In current implementation, can't subclass off built-in
classes. But can "wrap" them, see UserDict & UserList modules,
and see __getattr__() below.
Example:
class c (c_parent):
def __init__(self, name): self.name = name
def print_name(self): print "I'm", self.name
def call_parent(self): c_parent.print_name(self)
instance = c('tom')
print instance.name
'tom'
instance.print_name()
"I'm tom"
Call parent's super class by accessing parent's method
directly and passing "self" explicitly (see "call_parent"
in example above).
Many other special methods available for implementing
arithmetic operators, sequence, mapping indexing, etc.
Example: class C: "A description of C" def __init__(self): "A description of the constructor" # etc. Then c.__doc__ == "A description of C". Then c.__init__.__doc__ == "A description of the constructor".
lambda [param_list]: returnedExpr -- Creates an anonymous function. returnedExpr must be an expression, not a statement (e.g., not "if xx:...", "print xxx", etc.) and thus can't contain newlines. Used mostly for filter(), map(), reduce() functions, and GUI callbacks..List comprehensions
result = [expression for item1 in sequence1 [if condition1] [for item2 in sequence2 ... for itemN in sequenceN] ]is equivalent to:
result = [] for item1 in sequence1: for item2 in sequence2: ... for itemN in sequenceN: if (condition1) and further conditions: result.append(expression)
| Function | Result |
|---|---|
| __import__(name[, globals[, locals[, from list]]]) | Imports module within the given context (see lib ref for more details) |
| abs(x) | Return the absolute value of number x. |
| apply(f, args[, keywords]) | Calls func/method f with arguments args and optional keywords. |
| callable(x) | Returns 1 if x callable, else 0. |
| chr(i) | Returns one-character string whose ASCII code isinteger i |
| cmp(x,y) | Returns negative, 0, positive if x <, ==, > to y |
| coerce(x,y) | Returns a tuple of the two numeric arguments converted to a common type. |
| compile(string, filename, kind) | Compiles string into a code object. filename is used in error message, can be any string. It is usually the file from which the code was read, or eg. '<string>'if not read from file.kind can be 'eval' if string is a single stmt, or 'single' which prints the output of expression statements that evaluate to something else than None, or be 'exec'. |
| complex(real[, image]) | Builds a complex object (can also be done using J or j suffix,e.g. 1+3J) |
| delattr(obj, name) | deletes attribute named name of object obj <=> del obj.name |
| dir([object]) | If no args, returns the list of names in current local symbol table. With a module, class or class instance object as arg, returns list of names in its attr. dict. |
| divmod(a,b) | Returns tuple of (a/b, a%b) |
| eval(s[, globals[, locals]]) | Eval string s in (optional) globals, locals contexts. s must have no NUL's or newlines. s can also be a code object.Example: x = 1; incr_x = eval('x + 1') |
| execfile(file[, globals[, locals]]) | Executes a file without creating a new module, unlike import. |
| filter(function, sequence) | Constructs a list from those elements of sequence for whichfunction returns true. function takes one parameter. |
| float(x) | Converts a number or a string to floating point. |
| getattr(object, name[, default])) | Gets attribute called name from object,e.g. getattr(x, 'f') <=> x.f). If not found, raises AttributeError or returns default if specified. |
| globals() | Returns a dictionary containing current global variables. |
| hasattr(object, name) | Returns true if object has attr called name. |
| hash(object) | Returns the hash value of the object (if it has one) |
| hex(x) | Converts a number x to a hexadecimal string. |
| id(object) | Returns a unique 'identity' integer for an object. |
| input([prompt]) | Prints prompt if given. Reads input and evaluates it. |
| int(x[, base]) | Converts a number or a string to a plain integer. Optional base paramenter specifies base from which to convert string values. |
| intern(aString) | Enters aString in the table of "interned strings" and returns the string. Interned strings are 'immortals'. |
| isinstance(obj, class) | returns true if obj is an instance of class. If issubclass(A,B) then isinstance(x,A) => isinstance(x,B) |
| issubclass(class1, class2) | returns true if class1 is derived from class2 |
| len(obj) | Returns the length (the number of items) of an object (sequence, dictionary, or instance of class implementing __len__). |
| list(sequence) | Converts sequence into a list. If already a list, returns a copy of it. |
| locals() | Returns a dictionary containing current local variables. |
| long(x[, base]) | Converts a number or a string to a long integer. Optional base paramenter specifies base from which to convert string values. |
| map(function, list, ...) | Applies function to every item of list and returns a list of the results. If additional arguments are passed, function must take that many arguments and it is givent o function on each call. |
| max(seq) | Returns the largest item of the non-empty sequence seq. |
| min(seq) | Returns the smallest item of a non-empty sequence seq. |
| oct(x) | Converts a number to an octal string. |
| open(filename [, mode='r', [bufsize=implementation dependent]]) |
Returns a new file object. filename is the file name to be opened. mode indicates how the file is to be opened:
'r' for reading 'w' for writing (truncating an existing file) 'a' opens it for appending '+' (appended to any of the previous modes) open the file for updating (note that 'w+' truncates the file) 'b' (appended to any of the previous modes) open the file in binary mode bufsize is 0 for unbuffered, 1 for line-buffered, negative for sys-default, all else, of (about) given size. |
| ord(c) | Returns integer ASCII value of c (a string of len 1). Works with Unicode char. |
| pow(x, y [, z]) | Returns x to power y [modulo z]. See also ** operator. |
| range(start [,end [, step]]) |
Returns list of ints from >= start and < end. With 1 arg, list from 0..arg-1 With 2 args, list from start..end-1 With 3 args, list from start up to end by step |
| raw_input([prompt]) | Prints prompt if given, then reads string from std input (no trailing \n). See also input(). |
| reduce(f, list [, init]) | Applies the binary function f to the items oflist so as to reduce the list to a single value.I f init given, it is "prepended" to list. |
| reload(module) | Re-parses and re-initializes an already imported module. Useful in interactive mode, if you want to reload a module after fixing it. If module was syntactically correct but had an error in initialization, must import it one more time before calling reload(). |
| repr(object) | Returns a string containing a printable and if possible evaluable representation of an object. <=> `object` (using backquotes). Class redefineable (__repr__). See also str() |
| round(x, n=0) | Returns the floating point value x rounded to n digits after the decimal point. |
| setattr(object, name, value) | This is the counterpart of getattr().setattr(o, 'foobar', 3) <=> o.foobar = 3 Creates attribute if it doesn't exist! |
| slice([start,] stop[, step]) | Returns a slice object representing a range, with R/O attributes: start, stop, step. |
| str(object) | Returns a string containing a nicely printable representation of an object. Class overridable (__str__).See also repr(). |
| tuple(sequence) | Creates a tuple with same elements as sequence. If already a tuple, return itself (not a copy). |
| type(obj) | Returns a type object [see module types] representing the type of obj. Example: import types if type(x) == types.StringType: print 'It is a string'NB: it is recommended to use the following form:if isinstance(x, types.StringType): etc... |
| unichr(code) | Returns a unicode string 1 char long with given code. |
| unicode(string[, encoding[, error]]]) | Creates a Unicode string from a 8-bit string, using the given encoding name and error treatment ('strict', 'ignore',or 'replace'}. |
| vars([object]) | Without arguments, returns a dictionary corresponding to the current local symbol table. With a module,class or class instance object as argument returns a dictionary corresponding to the object'ss ymbol table. Useful with "%" formatting operator. |
| xrange(start [, end [, step]]) | Like range(), but doesn't actually store entire list all at once. Good to use in "for" loops when there is abig range and little memory. |
| zip(seq1[, seq2, ...]) | Returns a list of tuples where each tuple contains the nth element of each of the argument sequences. |
Standard methods & operators map to special '__methods__' and thus may be redefined (mostly in in user-defined classes), e.g.: class x: def __init__(self, v): self.value = v def __add__(self, r): return self.value + r a = x(3) # sort of like calling x.__init__(a, 3) a + 4 # is equivalent to a.__add__(4)
__init__(s, args) instance initialization (on construction) __del__(s) called on object demise (refcount becomes 0) __repr__(s) repr() and `...` conversions __str__(s) str() and 'print' statement __cmp__(s, o) Compares s to o and returns <0, 0, or >0. Implements >, <, == etc... __hash__(s) Compute a 32 bit hash code; hash() and dictionary ops __nonzero__(s) Returns 0 or 1 for truth value testing __getattr__(s, name) called when attr lookup doesn't find <name> __setattr__(s, name, val) called when setting an attr (inside, don't use "self.name = value" use "self.__dict__[name] = val") __delattr__(s, name) called to delete attr <name> __call__(self, *args) called when an instance is called as function.
See list in the operator module. Operator function names are provided with 2 variants, with or without
ading & trailing '__' (eg. __add__ or add).Numeric operations 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) s**o = __pow__(s,o) s&o = __and__(s,o) s^o = __xor__(s,o) s|o = __or__(s,o) s<<o = __lshift__(s,o) s>>o = __rshift__(s,o) nonzero(s) = __nonzero__(s) (used in boolean testing) -s = __neg__(s) +s = __pos__(s) abs(s) = __abs__(s) ~s = __invert__(s) (bitwise) s+=o = __iadd__(s,o) s-=o = __isub__(s,o) s*=o = __imul__(s,o) s/=o = __idiv__(s,o) s%=o = __imod__(s,o) s**=o = __ipow__(s,o) s&=o = __iand__(s,o) s^=o = __ixor__(s,o) s|=o = __ior__(s,o) s<<=o = __ilshift__(s,o) s>>=o = __irshift__(s,o)
Conversions int(s) = __int__(s) long(s) = __long__(s) float(s) = __float__(s) complex(s) = __complex__(s) oct(s) = __oct__(s) hex(s) = __hex__(s) coerce(s,o) = __coerce__(s,o) Right-hand-side equivalents for all binary operators exist; are called when class instance is on r-h-s of operator: a + 3 calls __add__(a, 3) 3 + a calls __radd__(a, 3)
All seqs and maps, general operations plus:
(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, general methods, plus: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] = [] seq * n = __repeat__(seq, n) s1 + s2 = __concat__(s1, s2) i in s = __contains__(s, i)Mappings, general methods, plushash(s) = __hash__(s) - hash value for dictionary references s[k]=v = __setitem__(s,k,v) del s[k] = __delitem__(s,k)
Lists & Dictionaries: __methods__ (list, R/O): list of method names of the object Modules: __doc__ (string/None, R/O): doc string (<=> __dict__['__doc__']) __name__(string, R/O): module name (also in __dict__['__name__']) __dict__ (dict, R/O): module's name space __file__(string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for modules statically linked to the interpreter) __path__(string/undefined, R/O): fully qualified package name when applies. Classes: [in bold: writable since 1.5.2] __doc__ (string/None, R/W): doc string (<=> __dict__['__doc__']) __name__(string, R/W): class name (also in __dict__['__name__']) __bases__ (tuple, R/W): parent classes __dict__ (dict, R/W): attributes (class name space) Instances: __class__ (class, R/W): instance's class __dict__ (dict, R/W): attributes User-defined functions: [bold: writable since 1.5.2] __doc__ (string/None, R/W): doc string __name__(string, R/O): function name func_doc (R/W): same as __doc__ func_name (R/O): same as __name__ func_defaults (tuple/None, R/W): default args values if any func_code (code, R/W): code object representing the compiled function body func_globals (dict, R/O): ref to dictionary of func global variables User-defined Methods: __doc__ (string/None, R/O): doc string __name__(string, R/O): method name (same as im_func.__name__) im_class (class, R/O): class defining the method (may be a base class) im_self (instance/None, R/O): target instance object (None if unbound) im_func (function, R/O): function object Built-in Functions & methods: __doc__ (string/None, R/O): doc string __name__ (string, R/O): function name __self__ : [methods only] target object __members__ = list of attr names: ['__doc__','__name__','__self__']) Codes: co_name (string, R/O): function name co_argcount (int, R/0): number of positional args co_nlocals (int, R/O): number of local vars (including args) co_varnames (tuple, R/O): names of local vars (starting with args) co_code (string, R/O): sequence of bytecode instructions co_consts (tuple, R/O): litterals used by the bytecode, 1st one is fct doc (or None) co_names (tuple, R/O): names used by the bytecode co_filename (string, R/O): filename from which the code was compiled co_firstlineno (int, R/O): first line number of the function co_lnotab (string, R/O): string encoding bytecode offsets to line numbers. co_stacksize (int, R/O): required stack size (including local vars) co_firstlineno (int, R/O): first line number of the function co_flags (int, R/O): flags for the interpreter bit 2 set if fct uses "*arg" syntax bit 3 set if fct uses '**keywords' syntax Frames: f_back (frame/None, R/O): previous stack frame (toward the caller) f_code (code, R/O): code object being executed in this frame f_locals (dict, R/O): local vars f_globals (dict, R/O): global vars f_builtins (dict, R/O): built-in (intrinsic) names f_restricted (int, R/O): flag indicating whether fct is executed in restricted mode f_lineno (int, R/O): current line number f_lasti (int, R/O): precise instruction (index into bytecode) f_trace (function/None, R/W): debug hook called at start of each source line f_exc_type (Type/None, R/W): Most recent exception type f_exc_value (any, R/W): Most recent exception value f_exc_traceback (traceback/None, R/W): Most recent exception traceback Tracebacks: tb_next (frame/None, R/O): next level in stack trace (toward the frame where the exception occurred) tb_frame (frame, R/O): execution frame of the current level tb_lineno (int, R/O): line number where the exception occured tb_lasti (int, R/O): precise instruction (index into bytecode) Slices: start (any/None, R/O): lowerbound stop (any/None, R/O): upperbound step (any/None, R/O): step value Complex numbers: real (float, R/O): real part imag (float, R/O): imaginary part XRanges: tolist (Built-in method, R/O): ?
| Variable | Content |
|---|---|
| argv | The list of command line arguments passed to a Python script. sys.argv[0] is the script name. |
| builtin_module_names | A list of strings giving the names of all modules written in C that are linked into this interpreter. |
| check_interval | How often to check for thread switches or signals (measured in number of virtual machine instructions) |
| exitfunc | User can set to a parameterless function. It will get called before interpreter exits. |
| last_type, last_value, last_traceback | Set only when an exception not handled and interpreter prints an error. Used by debuggers. |
| maxint | maximum positive value for integers |
| modules | Dictionary of modules that have already been loaded. |
| path | Search path for external modules. Can be modified by program. sys.path[0] == dir of script executing |
| platform | The current platform, e.g. "sunos5", "win32" |
| ps1, ps2 | prompts to use in interactive mode. |
| stdin, stdout, stderr | File objects used for I/O. One can redirect by assigning a new file object to them (or any object: with a method write(string) for stdout/stderr, or with a method readline() for stdin) |
| version | string containing version info about Python interpreter. (and also: copyright, dllhandle, exec_prefix, prefix) |
| version_info |