Professional Documents
Culture Documents
Python 2.4 Quick Reference Card Styles : keyword function/method type replaced_expression Types
basestring1 bool buffer complex dict exception file float
©2005-2007 — Laurent Pointal — License CC [by nc sa] variable literal module module_filename language_syntax
Notations : frozenset int list long object set slice str tuple type
CARD CONTENT f(…)→ return value f(…)➤ return nothing (procedure)
unicode xrange
1
basestring is virtual superclass of str and unicode.
Environment Variables........................1 Copying Containers...............................8 [x] for a list of x data, (x) for a tuple of x data, may have x{n}→
This doc uses string when unicode and str can apply.
Command-line Options....................... 1 Overriding Containers Operations........ 8 n times x data.
Files Extensions.................................. 1 Sequences.......................................... 8 Functions
Language Keywords............................1 Lists & Tuples........................................8 ENVIRONMENT VARIABLES Constructor functions of builtin types are directly accessible in
Builtins................................................ 1 Operations on Sequences..................... 8
Types.................................................... 1 Indexing................................................ 8 PYTHONCASEOK 1
no case distinction in module→file mapping builtins.
Functions.............................................. 1 Operations on mutable sequences....... 8 PYTHONDEBUG 1
= -d command-line option __import__ abs apply1 callable chr classmethod cmp coerce
Statements......................................... 1 Overriding Sequences Operations........ 8 PYTHONHOME Modify standard Python libs prefix and exec compile delattr dir divmod enumerate eval execfile
Blocks....................................................1 Mappings (dictionaries).......................8 prefix locations. Use <prefix>[:<execprefix>]. filter getattr globals hasattr hash help hex id input
Assignment Shortcuts...........................1 Operations on Mappings....................... 8 PYTHONINSPECT 1
= -i command-line option intern2 isinstance issubclass iter len locals map max min
Console & Interactive Input/Output.... 2 Overriding Mapping Operations............ 8 oct open ord pow property range raw_input reduce reload
Objects, Names and Namespaces...... 2 Other Mappings.....................................9 PYTHONOPTIMIZE 1
= -O command-line option
PYTHONPATH Directories where Python search when repr reversed round setattr sorted staticmethod sum
Identifiers..............................................2 Sets.....................................................9
importing modules/packages. Separator : super unichr vars zip
Objects and Names, Reference Operations on Sets................................9 1
Counting............................................... 2 Other Containers Structures, (posix) or ; (windows). Under windows use Use f(*args,**kargs) in place of apply(f,args,kargs).
2
Mutable/Immutable Objects..................2 Algorithms.......................................... 9 registry HKLM\Sofware\…. Don't use intern.
Namespaces......................................... 2 Array..................................................... 9 PYTHONSTARTUP File to load at begining of interactive sessions.
Constants, Enumerations......................2 Queue................................................... 9 STATEMENTS
Flow Control........................................ 2 Priority Queues..................................... 9
PYTHONUNBUFFERE 1 = -u command-line option
D One statement per line1. Can continue on next line if an expression
Condition...............................................2 Sorted List.............................................9
Loop...................................................... 2 Iteration Tools.......................................9 PYTHONVERBOSE 1
= -v command-line option or a string is not finished ( ( [ { """ ''' not closed), or with a \ at
Functions/methods exit.........................2 Date & Time........................................9 1
If set to non-empty value. end of line.
Exceptions............................................ 2 Module time.......................................... 9 Char # start comments up to end of line.
Iterable Protocol....................................2 Module datetime.................................10 COMMAND-LINE OPTIONS pass Null statement.
Interpretation / Execution................... 2 Module timeit......................................10
Functions Definitions & Usage............ 2 Other Modules.....................................10 python [-dEhiOQStuUvVWx] [-c cmd | -m mod | file | -] [args] assert expr[,message] Assertion check expression true.
Parameters / Return value.................... 2 Files.................................................. 10 -d Output debugging infos from parser. del name[,…] Remove name → object binding.
Lambda functions................................. 2 File Objects......................................... 10 -E Ignore environment variables. print [>>obj,][expr[,…][,] Write expr to sys.stdout2.
Callable Objects.................................... 2 Low-level Files.....................................10 -h Print help and exit.
Calling Functions...................................3 Pipes................................................... 10
exec expr [in globals [, Execute expr in namespaces.
-i Force interactive mode with prompt (even after script locals]]
Functions Control..................................3 In-memory Files.................................. 10
Decorators............................................ 3 Files Informations................................11
execution). fct([expr[,…]], Call any callable object fct with given
Types/Classes & Objects.....................3 Terminal Operations........................... 11 -O Optimize generated bytecode, remove assert checks. [name=expr[,…]] arguments (see Functions Definitions
Class Definition..................................... 3 Temporary Files.................................. 11 -OO As -O and remove documentation strings. [,*args][,**kwargs]) & Usage - p2).
Object Creation.....................................3 Path Manipulations..............................11 -Q arg Division option, arg in [old(default),warn,warnall,new].
Classes & Objects Relations..................3 Directories...........................................11 name[,…] = expr Assignment operator3.
-S Don't import site.py definitions module.
Attributes Manipulation.........................3 Special Files........................................ 12 1
Multiple statements on same line using ; separator - avoid if not
-t Warn inconsistent tab/space usage (-tt exit with error).
Special Methods....................................3 Copying, Moving, Removing............... 12
-u Use unbuffered binary output for stdout and stderr. necessary.
Descriptors protocol..............................3 Encoded Files......................................12 2
Copying Objects....................................3 Serialization........................................ 12 -U Force use of unicode literals for strings. Write to any specified object following file interface (write
Introspection.........................................3 Persistence..........................................12 -v Trace imports. method).
Modules and Packages........................3 Configuration Files.............................. 12 -V Print version number and exit. Write space between expressions, line-return at end of line except
Source encodings..................................3 Exceptions........................................ 12 -W arg Emit warning for arg with a final ,.
Special Attributes..................................3 Standard Exception Classes................12 3
Left part name can be container expression. If expr is a sequence
"action:message:category:module:lineno"
Main Execution / Script Parameters.... 4 Warnings.............................................13
Operators............................................4 Exceptions Processing........................ 13 -x Skip first line of source (fort non-Unix forms of #!cmd). of multiple values, can unpack into multiple names. Can have
Priority.................................................. 4 Encoding - Decoding......................... 13 -c cmd Execute cmd. multiple assignments of same value on same line : a = b = c =
Arithmetic Operators............................ 4 Threads & Synchronization............... 13 -m mod Search module mod in sys.path and runs it as main script. expr.
Comparison Operators..........................4 Threading Functions........................... 13 file Python script file to execute. Other statements (loops, conditions…) introduced in respective
Operators as Functions......................... 4 Threads...............................................13 args Command-line arguments for cmd/file, available in parts.
Booleans............................................. 4 Mutual Exclusion.................................13
sys.argv[1:]. Blocks
Numbers............................................. 4 Events................................................. 13
Operators..............................................4
Functions.............................................. 4
Semaphores........................................13
Condition Variables.............................13
FILES EXTENSIONS A : between statements defines dependant statements, written on
same line or written on following line(s) with deeper indentation.
Bit Level Operations........................... 5 Synchronized Queues......................... 13 .py=source, .pyc=bytecode, .pyo=bytecode optimized, .pyd=binary
Operators..............................................5 Process............................................. 13
Blocks of statements are simply lines at same indentation level.
module, .dll/.so=dynamic library. if x<=0 : return 1
Strings................................................ 5 Current Process...................................13
.pyw=source associated to pythonw.exe on Windows platform, to if asin(v)>pi/4 :
Escape sequences.................................5 Signal Handling...................................14
Unicode strings..................................... 5 Simple External Process Control......... 14 run without opening a console. a = pi/2
Methods and Functions.........................5 Advanced External Process Control.... 15 b = -pi/2
Formating..............................................6 XML Processing................................. 15 LANGUAGE KEYWORDS else :
Constants..............................................6 SAX - Event-driven.............................. 15 List of keywords in standard module keyword. a = asin(v)
Regular Expressions..............................6 DOM - In-memory Tree....................... 16 and as1 assert break class continue def del elif else b = pi/2-a
Localization...........................................7 Databases......................................... 17
Multilingual Support..............................7 Generic access to DBM-style DBs....... 17
except exec finally for from global if import in is Statement continuation lines don't care indentation.
Containers.......................................... 8 Standard DB API for SQL databases....17 lambda not or pass print raise return try while yield To avoid problems, configure your editor to use 4 spaces in place
1
Operations on Containers..................... 8 Bulk...................................................18 not reserved, but avoid to redefine it. of tabs.
Don't redefine these constants : None, True, False. Assignment Shortcuts
BUILTINS a += b a -= b a *= b a /= b
a //= b a %= b a **= b
Available directly everywhere with no specific import. Defined also
a &= b a |= b a ^= b a >>= b a <<= b
in module __builtins__.
Evaluate a once, and assign to a the result of operator before =
1a 1b 1c
applied to current a and b. Example : a%=b ≈ a=a%b globals() → dict: identifier→value of global namespace iter(callable,sentinel) → iterator returning callable() values up to
locals() → dict: identifier→value of local namespace sentinel
CONSOLE & INTERACTIVE INPUT/OUTPUT enumerate(iterable)→ iterator returning tuples (index,value) from iterable
Current scope → names directly usable. Searched in locals, then
print expression[,…] locals from enclosing definitions, then globals, then builtins. Iterators Objects Interface
input([prompt]) → evaluation of user input (typed data) Out-of-scope name → use the dotted attribute notation x.y (maybe next(self)→ next item1
raw_input([prompt]) → str: user input as a raw string x.y.z.t)… where x is a name visible within the current scope. __iter__(self)→ iterator object itself
Direct manipulation (redefinition) of stdin/stdout/stderr via sys
Class namespace → names defined in a class (class members). 1
When reach end of collection, raise StopIteration exception on
module :
sys.stdin sys.stdout sys.stderr Object namespace → names usable with object.name notation subsequent calls (ie. iterator usable only one time on a collection).
sys.__stdin__ sys.__stdout__ sys.__stderr__ (attributes, methods). Generators
All are files or files-like objects. The __xxx__ forms keep access to Namespaces can be nested, inner namespaces hidding identical Functions retaining their state between two calls. Return values
original standard IO streams. names from outer namespaces. using yield. Stop generation via simple return or via raise
Ctrl-C raises KeyboardInterrupt exception. dir([object]) → list: names defined in object namespace1 StopIteration.
_ → value of last expression evaluation vars([object]) → dict2: identifier:value of object as a namespace1 1) build generator from function : gen=generatorfct(args)
1
help([object]) ➤ print online documentation if object not specified use nearest namespace (locals). 2) use gen.next() values until StopIteration is raised.
2
sys.displayhook → (rw) fct(value) called to display value must not be modified.
sys.__displayhook__ → backup of original displayhook function Generator iterable expressions with : (x for x in iterable where
Constants, Enumerations
sys.ps1 → str: primary interpreter prompt cond)
Use uppercase and _ for constants identifiers (good practice). May
sys.ps2 → str: secondary (continuation) interpreter prompt define namespaces to group constants. Cannot avoid global/local Operations with/on Iterable
See external package ipython for an enhanced interactive Python name redefinition (can eventually define namespaces as classes See Operations on Containers (p8).
shell. with attributes access control - not in Python spirit, and execution
cost). See Iteration Tools (p9).
OBJECTS, NAMES AND NAMESPACES See third party modules pyenum for strict enum-like namespace. INTERPRETATION / EXECUTION
Identifiers FLOW CONTROL compile(string1,filename,kind2[,flags3[,dont_inherit3]]) → code object
Use : [a-zA-Z_][a-zA-Z0-9_]* eval(expression[,globals[,locals]]) → value: evaluation4 of expression
Special usage for underscore : Condition Loop
string
_xxx global not imported by import * if cond : inst for var[,…] in iterable : inst eval(code_object[,globals[,locals]]) → value: evaluation4 of code_object
_xxx implementation detail, for internal use (good [ elif cond : inst ] [ else : inst ] exec5 statements [in globals[,locals]] ➤ statements string1 executed4
practice) [ else : inst ] execfile(filename[,globals[,locals]]) ➤ file filename interpreted4
while cond : inst
__xxx 'private' class members, defined as There is no 'switch' or 1
[ else : inst ] Multi-line statements in source code must use \n as newline, and
_ClassName__xxx 'case'. must be terminated by a newline.
__xxx__ normally reserved by Python Can use if elif elif… else. Exit loop with break. 2
Kind relative to string content, 'exec' → sequence of statements,
Case is significant : This_Name != THIS_NAME. Can use a mapping with Go to next iteration with continue.
'eval' → single expression, 'single' → single interactive
Objects and Names, Reference Counting functions bound to cases. Loops else blocs only executed when
statement.
Data are typed objects (all data), names are dynamically bound to loop exit normally (without break). 3
Flags and dont_inherit are for future statements (see doc).
4
objects. Functions/methods exit In context of globals and locals namespaces.
5
= assignment statement bind result of right part evaluation into left Exit function/method with return [value] Exec is a langage statement, others are builtin functions.
part name(s)/container(s). Examples :
a = 3*c+5 a,b = ("Hello","World") x,y,tabz[i] = fct(i)
Exit from generator body with yield value FUNCTIONS DEFINITIONS & USAGE
Multiple returned values using tuple data.
s = "Hello" pi,e = 3.14,2.71 a,b = b,a def fctname([paramname[=defaultvalue][,…]] [,*args][,**kwargs]) :
Cannot yield within a try/finally block.
When an object is no longer referenced (by names or by instructions
containers), it is destroyed (its __del__ method is then called). Exceptions new.function(code,globals[,name[,argdefs]]) → python function (see
try : inst docs)
sys.getrefcount(object)→ int: current reference counter of object except [ except_class [,value ]] : inst Parameters / Return value
Standard module weakref define tools to allow objects to be …
Parameters are passed by references to objects.
garbage collected when necessary and dynamically re-created on- [ else : inst ]
You can modify values of mutable objects types.
demand. Can have a tuple of classes for except_class. Not specifying a class You cannot modify values of immutable objects types - as if they
Mutable/Immutable Objects catch all exceptions.
were passed by value.
Block else executed when try block exit normally.
Mutable objects can be modified in place. Immutable objects cannot Notation * → variable list of anonymous parameters in a tuple.
be modified (must build a new object with new value). try : inst Notation ** → variable list of named parameters in a dict.
Immutable : bool, int, long, float, complex, string, unicode, finally : inst Return value(s) with return [value[,…]]
tuple, frozenset, buffer, slice. Process finally block in all execution paths (normal or exception). For multiple values, return a tuple. If no return value specified or if
Mutable : list, set, dict and other high level class objects. raise exception_class[,value[,traceback]] end of function definition reached, return None value.
There is no constant definition. Just use uppercase names to identify raise exception_object Lambda functions
symbols which must not be modified. raise lambda param[,…] : expression
Namespaces Last form re-raise the currently catched exception in an exception Anonymous functions defined inline. Result of expression evaluation
Places where Python found names. handler. is returned (it must be an expression, no loop, no condition).
Builtins namespace → names from module __builtins__, already Iterable Protocol Expression uses values known at definition time (except for
available. Generic and simple protocol allowing to iterate on any collection of params).
Global namespace → names defined at module level (zero data. Callable Objects
indentation). Objects of class defining __iter__ or __getitem__ are iterable
Local namespace → names defined in methods/functions. Objects having a __call__ method can be used as functions.
(directly usable in for loops). Methods bound to objects can be used as functions : f = o.meth
del name ➤ remove existing name from namespace (remove object __iter__(self) → iterator on self callable(x) → bool: test x callable with x(…)
binding) iter(object) → iterator on iterable object
2a 2b 2c
Calling Functions Attributes Manipulation default values are None and empty list.
[name=] fctname([expr[,…]][,name=expr[,…][,*args][,**args]) object.name = value Copy Protocol
Anonymous parameters passed in parameters order declaration. setattr(object,name,value) ➤ object attribute set to value
__copy__(self)→ value: shallow copy of self, called by
Params having default value can be omitted. object.name → value of object attribute
Notation * → pass variable list of anonymous parameters in a copy.copy(…)
getattr(object,name[,default])→ value of object attribute
tuple. __deepcopy__(self,memo)→ value: deep copy of self, called by
del object.name
Notation ** → pass variable list of named parameters in a dict. copy.deepcopy(…)
delattr(object,name) ➤ object attribute removed
For copying, objects can define pickling protocol too (see Files -
Functions Control Special Methods Serialization - p12), in place of __copy__ and __deepcopy__.
sys.getrecursionlimit()→ int: current recursion limit for functions Other special overridable __xxx___ methods are listed in respective Introspection
sys.setrecursionlimit(limit) ➤ set recursion limit for functions sections.
Beyond this documentation. Many __xxx___ attributes are defined,
Decorators Object Life some are writable (see other docs).
Glue code (functions) called at functions and methods definitions __new__(classref,initargs…)→ object of classref type, already See standard module inspect to manipulate these data.
time, return the final function/method (generally with wrapping initialized1 Example of Introspection Attributes
code). __init__ (self,initargs…)➤ called to initialize object with initargs
@decoratorname [(decorator_arguments)] […] Note: classes are objects too!
__del__ (self)➤ called when object will be destroyed
def fct(fct_rguments):… 1
__base__ → list: parent classes of a class
If don't return a classref object, then object.__init__ is called with
__slots__ → tuple: allowed objects attributes names1 of a class
@dec1 @dec2(args) @dec3 def fct(…):… initargs.
__class__ → class/type: object's class
def fct(…):… like fct = dec1(dec2(args)(dec3(fct)))) Object Cast
➤ __dict__ → dict: defined attributes (object namespace) of an instance
See page PythonDecoratorLibrary in python.org Wiki for some __repr__(self)→ str: called for repr(self) and `self` __doc__ → string: documentation string of a package, module, class,
decorators definitions. __str__(self) → str: called for str(self) and print self function
__coerce__(self,other) → value, called for coerce(self,other) __name__ → str: object definition name of a function
TYPES/CLASSES & OBJECTS Object Hash Key
__file__ → string: pathname of loaded module .pyc, .pyo or .pyd
1
All data are typed objects relying to classes. List of allowed attributes names. Usage discouraged.
__hash__(self)→ int: 32 bits hash code for object, used for
type(o) → type: type object of o
hash(obj)and quick dict mapping keys comparison - default
Standard module types define type objects for builtins types.
implementation use hash(id(self)) MODULES AND PACKAGES
Class Definition File gabuzo.py ➤ module gabuzo.
Attributes access
class classname [(parentclass[,…])] : Directory kramed/ with a file __init__.py ➤ package kramed.
varname = expr ➤ varname defined in classname namespace See also "Descriptors protocol" infra.
__getattr__(self,name)→ value, called for undefined attributes Can have sub-packages (subdirectories having __init__.py file).
def metname(self[,…]): ➤ define methods like functions Searched in the Python PATH.
Support multiple inheritance. Can inherit from builtin class. __getattribute__(self, name)→ value, always called
Current Python PATH stored in sys.path list. Contains directories
Inherit at least from object base class => Python 'new style class'. __setattr__(self, name, value) ➤ called for obj.name=value
and .zip files paths. Built from location of standard Python modules,
First parameter of methods is target object, standard use self __delattr__(self, name) ➤ called for del obj.name
PYTHONPATH environment variable, directory of main module given
name. __call__(self, *args, **kwargs)→ value, called for obj(…) on command line, data specified in lines of .pth files found in Python
Access class members via class name, object members via self. Static method / Class method home directory, and data specified in registry under Windows.
This doc consider you use new style class (inheriting from object). Use standard decorators (see Decorators p3). Current list of loaded modules stored in sys.modules map (main
new.classobj(name,baseclasses,dict) → new class (see docs) class ClassName : module is under key __main__).
new.instancemethod(fct,instance,class) → new method: bound to @staticmethod import module [as alias] [,…]
instance it it is not None, see docs def methodname(…): … from module import name [as alias] [,…]
Metaclass @classmethod from module import *
def methodname(classref,…): … reload(module) ➤ module is reloaded (but existing references still refer
Class definition create a new type. It can be done 'by hand' with : old module content)
x = type('classname',(parentclass,[…]),{varname:expr[,…]} Descriptors protocol
new.module(name[,doc]) → new module object.
def metname(self[,…]): Descriptors are attribute objects controling access to attributes
Import can use package path (ex:from encoding.aliases
x.metname = metname values. They must define some of following methods :
import…).
This allow creation of metaclass class (class building other class). __get__(self,obj,ownerclass)→ attribute value for obj
Direct import from a package use definitions from __init__.py file.
Object Creation __set__(self,obj,value) ➤ modify attribute in obj, set to value
Very careful with import * as imported names override names
__delete__(self,obj) ➤ remove attribute from obj
obj = ClassName(initargs…) already defined.
In these methods self is the descriptor object, and obj is the target
In case of exception during initialization, object is destroyed when To limit your modules names exported and visible by import *,
object which attribute is manipulated.
exiting init code (reference counter reach zero). define module global __all__ with list of exported names (or use
new.instance(class[,dict]) → object: create new class instance without Properties global names _xxx).
calling __init__ method, dict is initial object attributes A descriptor to directly bind methods/functions to control attribute See __import__ builtin function, and modules imp, ihooks.
Classes & Objects Relations access. Use builtin type property with init args. __import__(modulename[, globals[,locals[,lnameslist]]])
isinstance(obj,classinfo) → bool: test object kind of type/class class MyClass : Source encodings
classinfo attributename = property(getter,setter,deleter,description) See PEP 263. Declare source files encoding in first or second line in
issubclass(aclass,aparent) → bool: test same class or parent Each init arg default to None (ie. undefined). a special comment.
relationship Copying Objects # -*- coding: encoding_name -*-
Prefer isinstance() to type() for type checking. Assignment only duplicate references. To shallow copy an object If this is not specified, Python use sys.getdefaultencoding()
Parent class methods are not automatically called if overriden in (build a new one with same values - referencing same content), or value (see modules sitecustomize.py and user.py).
subclass - they must be explicitly called if necessary. to deep copy an object (deep-copying referenced content), see It is important to specify encoding of your modules as u"…" strings
Call parent methods via super function : object copy methods, and functions in standard module copy. use it to correctly build unicode literals.
super(ThisClass,self).methodname(self,args…) copy.copy(object)→ value: shallow copy of object Special Attributes
Or the old way, via parent class namespace : copy.deepcopy(object[[,memo],_nil])→ value: deep copy of object1 __name__ → str: module name, '__main__' for command-line called
1
ParentClass.methodname(self,args…) Params memo and nil are used in recursive deepcopy, their script
3a 3b 3c
__file__ → string: pathname of compiled module loaded x<y<=z>t. True : if not false. True → 1.
Builtin function cmp(o1,o2) → -1 (o1 < o2), 0 (o1 == o2), 1 (o1 > o2) bool(expr) → True | False
MAIN EXECUTION / SCRIPT PARAMETERS Logical not : not expr
Comparison Overriding
The 'main' module is the module called via command-line (or Logical and : expr1 and expr2
executed by shell with first script line #! /bin/env python). __lt__(self, other)→ bool1: called for self < other Logical or : expr1 or expr2
Command-line parameters are available in sys.argv (a python __le__(self, other)→ bool1: called for self <= other Logical and and or use short path evaluation.
list). __gt__(self, other)→ bool1: called for self > other
__ge__(self, other)→ bool1: called for self >= other Bool Cast Overriding
At end of module, we may have :
if __name__=='__main__' : __eq__(self, other)→ bool1: called for self == other __nonzero__(self) → bool: test object itself1
# main code __ne__(self, other)→ bool1: called for self != other 1
If __nonzero__ undefined, look at __len__, else object is true.
# generally call a 'main' function: and for self <> other
mainfunction(sys.argv[1:]) __cmp__(self,other)→ int: called for self compared to other, NUMBERS
# or in lib modules, execute test/demo code... self<other→value<0, self==other→value=0, self>other→value>0 Builtin integer types : int (like C long), long (unlimited integer)
Execution exit after last main module instruction (in multithread,
1
Any value usable as boolean value, or a NotImplemented value if int(expr[,base=10]) → int: cast of expr
wait also for end of non-daemon threads), unless interactive mode cannot compare with such other type. long(expr[,base=10]) → long: cast of expr
is forced. Operators as Functions Builtin floating point types : float (like C double), complex (real and
Can force exit with calling sys.exit(code), which raise a imaginary parts are float).
Operators are also defined as functions in standard operator
SystemExit exception - see Current Process - Exiting (p13). float(expr) → float: representation of expr
module.
complex(x[,y]) → complex: number: x+yj
OPERATORS Comparison [x+]yj → complex: number, ex: 3+4j -8.2j
Deal with arithmetic, boolean logic, bit level, indexing and slicing. lt(a,b) = __lt__(a,b) ne(a,b) = __ne__(a,b) c.real → float: real part of complex number
Priority le(a,b) = __le__(a,b) ge(a,b) = __ge__(a,b) c.img → float: imaginary part of complex number
eq(a,b) = __eq__(a,b) gt(a,b) = __gt__(a,b) c.conjugate() → complex: conjugate of complex number (real,-img)
1 (a,…) [a,…] 6 x+y 11 x<y x<=y x>y x>=y x==y x!=y
Logical / Boolean Maximum int integer in sys.maxint.
{a:b,…} `…` x-y x<>y x is y x is not y x in s Automatic conversions between numeric types.
x not in s not_(o) = __not__(o) and_(a,b) = __and__(a,b) Automatic conversions from int to long when result overflow max
2 s[i] s[i:j] 7 x<<y 12 not x truth(o) or_(a,b) = __or__(a,b) int.
s.attr f(…) x>>y is_(a,b) xor(a,b) = __xor__(a,b) Direct conversions from/to strings from/to int, long… via types
is_not(a,b) constructors.
3 +x -x ~x 8 x&y 13 x and y
Arithmetic Type Decimal defined in standard module decimal.
4 x**y 9 x^y 14 x or y Base fixed type compact storage arrays in standard module array.
abs(o) = __abs__(o) truediv(a,b) = __truediv__(a,b)
5 x*y x/y x%y 10 x|y 15 lambda args:expr
add(a,b) = __add__(a,b) floordiv(a,b) = __floordiv__(a,b) Operators
Arithmetic Operators sub(a,b) = __sub__(a,b) neg(o) = __neg__(o) -x +x x+y x-y x*y x/y 1 x//y 1 x%y 2 x**y 2
1
Can be defined for any data type. mul(a,b) = __mul__(a,b) pos(o) = __pos__(o) With from __future__ import division, / is true division
div(a,b) = __div__(a,b) pow(a,b) = __pow__(a,b) (1/2→0.5), and // is floor division (1//2→0). Else for integers / is
Arithmetic Overriding
mod(a,b) = __mod__(a,b) still floor division.
__add__(self,other) → value: called for self + other 2
% is remainder operator, ** is power elevation operator (same as
__sub__(self,other) → value: called for self - other Bit Level
pow).
__mul__(self,other) → value: called for self * other lshift(a,b) = __lshift__(a,b)
Functions
__div__(self,other) → value: called1 for self / other rshift(a,b) = __rshift__(a,b)
inv(o) = invert(o) = __inv__(o) = __invert__(o) Some functions in builtins.
__truediv__(self,other) → value: called2 for self / other
abs(x) → absolute value of x
__floordiv__(self,other) → value: called for self // other Sequences
__mod__(self,other) → value: called for self % other divmod(x,y) → (x/y,x%y)
concat(a,b) = __concat__(a,b) oct(integer) → str: octal representation of integer number
__divmod__(self,other) → value: called for divmod(self,other)
contains(a,b) = __contains__(a,b) hex(integer) → str: hexadecimal representation of integer number
__pow__(self,other) → value: called for self ** other
countOf(a,b) Representation formating functions in strings Formating (p6) and
__nonzero__(self)→ value: called for nonzero(self)
indexOf(a,b) Localization (p7).
__neg__(self) → value: called for -self
repeat(a,b) = __repeat__(a,b) Math Functions
__pos__(self) → value: called for +self
setitem(a,b,c) = __setitem__(a,b,c)
__abs__(self) → value: called for abs(self) Standard floating point functions/data in standard math module.
getitem(a,b) = __getitem__(a,b)
__iadd__(self,other) ➤ called for self += other acos(x) → float: radians angle for x cosinus value : [-1…1] →[0…π]
delitem(a,b) = __delitem__(a,b)
__isub__(self,other) ➤ called for self -= other asin(x) → float: radians angle for x sinus value : [-1…1] →[-π/2…+π/2]
setslice(a,b,c,v) = __setslice__(a,b,c,v)
__imul__(self,other) ➤ called for self *= other atan(x) → float: radians angle for x tangent value : [-∞…∞] →]-π/2…
getslice(a,b,c) = __getslice__(a,b,c)
__idiv__(self,other) ➤ called1 for self /= other +π/2[
delslice(a,b,c) = __delslice__(a,b,c)
__itruediv__(self,other) ➤ called2 for self /= other atan2(x,y) → float: randians angle for x/y tangent value
__ifloordiv__(self, other) ➤ called for self //= other Type Testing
ceil(x) → float: smallest integral value >= x
__imod__(self,other) ➤ called for self %= other These functions must be considered as not reliable. cos(x) → float: cosinus value for radians angle x
__ipow__(self,other) ➤ called for self **= other isMappingType(o)
1 cosh(x) → float: hyperbolic cosinus value for radians angle x
without / 2 with from __futur__ import division isNumberType(o)
Binary operators __xxx__ have also __rxxx__ forms, called when isSequenceType(o) exp(x) → float: exponential of x = ex
target object is on right side. fabs(x) → float: absolute value of x
Attribute and Item Lookup
floor(x) → float: largest integral value <= x
Comparison Operators
attrgetter(attr) → fct: where fct(x)→x.attr fmod(x,y) → float: modulo = remainder of x/y
Operators can compare any data types. itemgetter(item) → fct: where fct(x)→x[item]
Compare values with < <= > >= == != <>. frexp(x) → (float,int): (m,y) m mantissa of x, y exponent of x — where
Test objects identity with is and is not (compare on id(obj)). BOOLEANS x=m*2y
Direct composition of comparators is allowed in expressions : ldepx(x,i) → float: x multiplied by 2 raised to i power: x * 2i
False : None, zero numbers, empty containers. False → 0. log(x) → float: neperian logarithm of x
4a 4b 4c
log10(x) → float: decimal logarithm of x Advanced binary structures mapping and manipulation in third decimal(unichr[,default]) → int: decimal value - may raise ValueError
modf(x) → (float{2}): (f,i) f signed fractional part of x, i signed integer party modules : ctypes, xstruct, pyconstruct, … digit(unichr[,default]) → int: digit value - may raise ValueError
part of x Bit Level Overriding numeric(unichr[,default]) → float: numeric value - may raise
pow(x,y) → float: x raised to y power (xy) ValueError
__and__(self,other) → value: for self & other
sin(x) → float: sinus value for radians angle x category(unichr) → str: general unicode category of char
__or__(self,other) → value: for self | other
sinh(x) → float: hyperbolic sinus value for radians angle x bidirectional(unichr) → str: bidir category of char, may be empty
__xor__(self,other) → value: for self ^ other
sqrt(x) → float: square root of x (√x) string
__lshift__(self,other) → value: for self << other combining(unichr) → str/0: canonical combining class of char as integer
tan(x) → float: tangent value for radians angle x __rshift__(self,other) → value: for self >> other east_asian_width(unichr) → str: east asian width
tanh(x) → float: hyperbolic tangent value for radians angle x __invert__(self) → value: for ~self mirrored(unichr) → int: mirrored property in bidi text, 1 if mirrored else
pi → float: value of π (pi=3.1415926535897931) __iand__(self,other) ➤ called for self &= other 0
e → float: value of neperian logarithms base __ior__(self,other) ➤ called for self |= other decomposition(unichr) → str: decomposition mapping, may be empty
(e=2.7182818284590451) __ixor__(self,other) ➤ called for self ^= other str
Module cmath provides similar functions for complex numbers. __ilshift__(self,other) ➤ called for self <<= other normalize(form, unistr) → str: normal form of string - form in 'NFC',
Random Numbers __irshift__(self,other) ➤ called for self >>= other 'NFKC', 'NFD', 'NFKD'
Randomization functions in standard random module. Module STRINGS unidata_version → str: version of Unicode database used
functions use an hidden, shared state, Random type generator Methods and Functions
Simple quoted 'Hello' or double-quoted "Hello".
(uniform distribution). From builtins (see also oct and hex functions for integers to
Use triple [simple|double] quotes for multi-lines strings :
Functions also available as methods of Random objects. strings) :
"""Hello,
seed([x]) ➤ initialize random number generator how are you ?""" len(s) → int: number of chars in the string
random()→ float: random value in [0.0, 1.0[ Strings are immutable (once created a string cannot be modified in Most string methods are also available as functions in the standard
randint(a,b)→ int: random value in [a, b] place). string module.
uniform(a, b)→ float: random value in [a, b[ Strings can contain binary data, including null chars (chars of code s.capitalize() → string with first char capitalized1
getrandbits(k)→ long: with k random bits 0). s.center(width[,fillchar]) → string centered
randrange([start,]stop[,step])→ int: random value in range(start, Strings are sequences, see Indexing (p8) for chars indexation s.count(sub[,start[,end]]) → int: count sub occurences
stop, step) (slicing) and other operations. s.decode([encoding[,errors]]) → unicode: text decoded - see encodings
choice(seq)→ value: random item from seq sequence chr(code)→ str: string of one char (p13)
shuffle(x[,rndfct]) ➤ items of x randomly reordered using rndfct() ord(char)→ int: code s.encode([encoding[,errors]]) → str: text encoded - see encodings
sample(population,k)→ list: k random items from polulation str(expr)→ str: readable textual representation of expr - if available (p13)
Alternate random distributions : betavariate(alpha,beta), `expr` → str: readable textual representation of expr - if available s.endswith(suffix[,start[,end]]) → bool: test text ending
expovariate(lambd), gammavariate(alpha,beta), repr(expr)→ str: evaluable textual representation of expr - if available s.expandtabs([tabsize]) → string with tabs replaced by spaces
gauss(mu,sigma), lognormvariate(mu, sigma), Escape sequences s.find(sub[,start[,end]]) → int/-1: offset of sub
normalvariate(mu,sigma), vonmisesvariate(mu,kappa), s.index(sub[,start[,end]]) → int: offset of sub - may raise ValueError
\a - bell \v - vertical tab
paretovariate(alpha), weibullvariate(alpha,beta). s.isalnum() → bool: non empty string with all alphanumeric chars1
\b - backspace \' - single quote
Alternate random generator WichmannHill class. s.isalpha() → bool: non empty string with all alphabetic chars1
\e - escape \" - double quote
Direct generator manipulation : getstate(), setstate(state), s.isdigit() → bool: non empty string with all digit chars1
\f - form feed \\ - backslash
jumpahead(n). s.islower() → bool: non empty string with all lower chars1
\n - new line \ooo - char by octal ooo value
In module os, see : s.isspace() → bool: non empty string with all space chars1
\r - carriage return \xhh - char by hexadecimal hh value
os.urandom(n) → str: n random bytes suitable for cryptographic use s.istitle() → bool: non empty string with titlecase words1
\t - horizontal tab \<newline> - continue string on next line.
Other Math Modules s.isupper() → bool: non empty string with all upper chars1
And for Unicode strings : s.join(seq) → string: seq[0]+s+seq[1]+s+…+seq[n-1]
Advanced matrix, algorithms and number crunching in third party \uxxxx - unicode char by 16 bits hexadecimal xxxx value. s.ljust(width[,fillchar]) → text string left aligned2
modules like numpy (evolution of numarray / Numeric), gmpy \Uxxxxxxxx - unicode char by 32 bits hexadecimal xxxxxxxx value. s.lower() → text string lowered1
(multiprecision arithmetic), DecInt, scipy, pyarray, … \N{name} - unicode char by name in the Unicode database. s.lstrip([chars]) → string text with leading chars2 removed
See sites SciPy, BioPython, PyScience,… Keep \ escape chars by prefixing string literals with a r (or R) - for s.replace(old,new[,count]) → string with count firsts old replaced by
'raw' strings (note : cannot terminate a raw string with a \). new
Numbers Casts Overriding
Unicode strings s.rfind(sub[,start[,end]]) → int/-1: last offset of sub
__int__(self) → int: called for int(self)
Quoted as for str, but with a u (or U) prefix before the string : s.rindex(sub[,start[end]])→ int: last offset of sub - may raise
__long__(self) → long: called for long(self)
u"Voiçi" ValueError
__float__(self) → float: called for float(self)
U"""Une bonne journée s.rjust(width[,fillchar]) → string text right aligned2
__complex__(self) → complex: called for complex(self)
en perspective.""" s.rsplit([sep[,maxsplit]])→ [string]: rightmost words delim. by sep2
__oct__(self) → str: called for oct(self)
Can mix strings prefixs r (or R) and u (or U). s.rstrip([chars]) → string with trailing chars2 removed
__hex__(self) → str: called for hex(self)
You must define your source file encoding so that Python knows s.split([sep[,maxsplit]]) → [string]: words delimited by sep2
__coerce__(self,other) → value: called for coerce(self,other)
how to convert your source literal strings into internal unicode s.splitlines([keepends]) → [string]: list of text lines
BIT LEVEL OPERATIONS strings. s.startswith(suffix[,start[,end]]) → bool: test text begining
unichr(code) → unicode: string of one char s.strip([chars]) → string text with leading+trailing chars2 removed
Work with int and long data. ord(unicode char) → int: unicode code s.swapcase() → string with case switched1
Operators unicode(object[,encoding[,errors]]) → unicode: unicode s.title() → string with words capitalized1
~x → inverted bits of x sys.maxunicode → int: maximum unicode code=fct(compile time s.translate(table[,deletechars]) → string: cleaned, converted3
x^y → bitwise exclusive or on x and y option) s.upper() → string uppered1
x&y → bitwise and on x and y Unicode Chars Informations s.zfill(witdh) → string: string prefixed with zeroes to match width
x|y → bitwise or on x and y 1
Locale dependant for 8 bits strings.
Module unicodedata contains informations about Unicode chars 2
x<<n → x shifted left by n bits (zeroes inserted) Default chars/separator/fillchar is space.
properties, names. 3
x>>n → x shifted right by n bits (zeroes inserted) For str table must be a string of 256 chars - see
lookup(name) → unicode: unicode char from its name
string.maketrans(). For Unicode no deletechars, and table must
Binary structures manipulations in standard module struct. name(unichr[,default]) → str: unicode name - may raise ValueError
5a 5b 5c
be a map of unicode ordinals to unicode ordinals. lowercase → str: lowercase a-z chars1 \d ➤ match char class decimal digit [0-9]
Formating octdigits → str: 0-7 octal digit chars \D ➤ match char class non-digit [^0-9]
Use % operator between format string and arguments : string%args punctuation → str: ascii chars considered as punctuation in C locale \s ➤ match char class whitespace [ \t\n\r\f\v]
Formating string contains %[(name)][flag][width][.precision]code printable → str: printable chars \S ➤ match char class non-whitespace [^ \t\n\r\f\v]
If not use %(name)… → args = single value or tuple of values. uppercase → str: uppercase A-Z chars1 \w ➤ match char class alphanumeric [a-zA-Z0-9_]
whitespace → str: whitespace chars (spc, tab, cr, lf, ff, vt) \W ➤ match char class non-alphanumeric [^a-zA-Z0-9_]
If use %(name)… → args = mapping with name as keys.
capwords(s) → str: split → capitalize → join \Z ➤ match end of string
For mapping, args can be an object with __getitem__ method - see
maketrans(from,to) → translation table usable in str.translate - from and \a \b \f \n \r \t \v \x \\ ➤ same as string escapes
Overriding Mapping Operations (p8).
to must have same length \c ➤ for other c chars, match char c
Format char codes 1
Definition is locale dependant. 1
Depends on UNICODE flag.
d signed int. decimal : -324 i signed int. decimal : -324 Regular Expressions 2
Depends on LOCALE flag.
o unsigned octal : 774 u unsigned decimal 6953 3
When out of char class definition ([…])
Standard module re has a powerfull regexp engine. See regexp
x unsigned hexa : f3a X unsigned hexa : F3A HOWTO at http://www.amk.ca/python/howto/regex/. Flag Options
e float. point exp. : -3.256e-12 E float. point exp. : -3.256E-12 Use raw string r"…" notation.
f float. point dec. : -0.0000032 F float. point dec. : -0.0000032 IGNORECASE (I) : case insensitive expression - not locale dependant.
See also external projects pyparsing, PLY (Python Lex-Yacc), tpg
g like e or f G like E or F LOCALE (L) : make \w \W \b \B locale dependant.
(Toy Parser Generator)…
c character (1 char str or code) % %% → % MULTILINE (M) : ^ and $ match begining/end of string and lines. Else
r s Expressions ^ and $ match only beginning and end of string.
object format like repr(object) object format like str(object)
Metacharacters : . ^ $ * + ? { } [ ] \ | ( ), may use \ DOTALL (S) : make . match any char including newline. Else newline
Templates
escape. excluded.
With string.Template objects. Use common $ syntax : $$ ➤ single . ➤ match any character except a newline (including newline with DOTALL UNICODE (U) : make \w \W \b \B unicode dependant.
$ ; $name or ${name} ➤ value for name. option) VERBOSE (X) : ignore whitespaces and make # starting comments
tmpl = string.Template(template_string) ^ ➤ match start of string (and start of lines with MULTILINE option) (except when space and # are escaped or in char class).
tmpl.substitute(mapping[,**kwargs]) → string: template filled $ ➤ match end of string (and end of lines with MULTILINE option) Matching and Searching
tmpl.safe_substitute(mapping[,**kwargs]) → string: template filled expr* ➤ match 0 or more repetitions of expr (as much as possible)
tmpl.template → string expr+ ➤ match 1 or more repetitions of expr (as much as possible) Can use re functions, or compile expressions into SRE_Pattern
Can subclass Template to build your own templating (see doc, expr? ➤ match 0 or 1 expr objects and use their methods.
sources). expr*? ➤ match like expr* but as few as possible See Flag Options supra for flags parameters.
See also modules formatter. search(pattern,string[,flags])→ MatchObject/None: scan throught
expr+? ➤ match like expr+ but as few as possible
string to find substrings matching pattern
Wrapping expr?? ➤ match like expr? but as few as possible
match(pattern,string[,flags])→ MatchObject/None: try to match string
expr{m} ➤ match m repetitions of expr
Module textwrap has a TextWrapper class and tool functions. with pattern
expr{[m],[n]} ➤ match from m to n repetitions of expr, missing m default
tw = textwrap.TextWrapper([…]) → new text wrapper using named split(pattern,string[,maxsplit=0])→ [string]: split string by occurences
to 0 and missing n default to infinite
params as corresponding attributes values of pattern - if maxsplit specified, remainder is put in last item of list
expr{[m],[n]}? ➤ match like expr{[m],[n]} but as few as possible
tw.width → int: max length of wrapped lines (default 70) findall(pattern,string[,flags])→ [string]/[(string)]: find non-
[set] ➤ match one char in the set defined by :
tw.expand_tabs → bool: replace tabs by text.expandtabs() (default overlapping substrings matching pattern - eventually empty matchs -
^ → at begining, invert set definition return list of tuples if pattern has groups
True)
x-y → chars from x to y finditer(pattern,string[,flags])→ iterator over [MatchObject] - same
tw.replace_whitespace → bool: replace each whitespace by space
\x → see Escape sequences for strings (p5) as findall but with an iterator
(default True)
\- , \] → chars - and ] (- and ] at the beginning match - and ] sub(pattern,repl,string[,count=0])→ string: replace substrings matching
tw.initial_indent → string: prepend to first wrapped line (default '')
chars) pattern by repl - repl as string can contain back references1 to identified
tw.subsequent_indent → string: prepend to other wrapped lines
x → char x (including other re metacharacters) substring - repl as fct(MatchObject) return replacement string - pattern
(default '')
exprA|exprB ➤ match exprA or exprB, short path evaluation may be RE_Pattern object
tw.fix_sentence_endings → bool: try to separate sentences by two
(expr) ➤ match expr and build a numbered group subn(pattern,repl,string[,count=0])→ (string,int): same as sub, 2nd
spaces (default False)
(?[i][L][m][s][u][x]) ➤ (at least one ot iLmsux char) group match empty item is count of substitutions
tw.break_long_words → bool: break words longer than width (default
string, modify options flags for entire expression - see I L M S U X escape(string)→ string: non-alphanumerics backslashed
True)
options
tw.initial_indent → string: prepend to first wrapped line (default '') If you need to reuse a pattern, compile it one time for all.
(?:expr) ➤ match expr but dont build a group
tw.wrap(text) → [string]: list of text lines, each with max width length - pat = re.compile(pattern[,flags])→ RE_Pattern object
(?P<name>expr) ➤ match expr and build a group numbered and named
no final newline pat.match(string[,pos[,endpos]]) → same as match function2
(name must be valid Python identifier)
tw.fill(text) → string: whole text, lines wrapped using newlines pat.search(string[,pos[,endpos]]) → same as search function2
(?P=name) ➤ match text matched by earlier group named name
Two convenient functions use temporary TextWrapper, built using pat.split(string[,maxsplit=0])→ same as split function2
(?#text) ➤ no match, text is just a comment
named parameters corresponding to attributes. pat.findall(string[,pos[,endpos]])→ same as findall function2
(?=expr) ➤ match if match expr but don't consume input
wrap(text[,width=70[,…]]) → [string] pat.finditer(string[,pos[,endpos]])→ same as finditer function2
(?!expr) ➤ match if doesn't match expr but don't consume input
fill(text[,width=70[,…]]) → string pat.sub(repl,string[,count=0])→ same as sub function
(?<=expr) ➤ match if current position is immediatly preceded by a match
dedent(text) → string: remove uniform whitespaces at beginning of text pat.subn(pattern,repl,string[,count=0])→ same as subn function
for fixed length pattern expr
lines pat.flags → int: flags used at compile time
(?<!expr) ➤ match if current position is immediatly not preceded by a
Constants match for fixed length pattern expr pat.pattern → string: pattern used at compile time
Standard module string provide several constants (do not modify, (?(num/name)yesexpr[|noexpr]) ➤ try to match yesexpr if group pat.groupindex → dict: mapping of group names to group numbers
they are used in string manipulation functions) and some str num/name exists, else try to match noexpr Several functions/methods return MatchObject objects.
functions are not available as methods. Escape Sequences m.expand(template)→ string: do backslash substitution on template (like
ascii_letters → str: lowercase and uppercase chars sub method) using match object groups values
ascii_lowercase → str: lowercase a-z chars \n \nn ➤ match3 group number n (nn) where first n≠0
m.group([group[,…]])→ string/(string): subgroups of the match from
ascii_uppercase → str: uppercase A-Z chars \ooo \0o ➤ match3 char with octal value ooo (0o)
numbers or names
digits → str: 0-9 decimal digit chars \A ➤ match only at the start of the string
m.groups([default=None])→ (string): all subgroups of the match -
hexdigits → str: 0-9a-fA-F hexadecimal digit chars \b ➤ match3 empty string at beginning or end of a word1+2
default give access to subgroups not in the match
letters → str: lowercase and uppercase chars1 \B ➤ match empty string not at beginning or end of a word1+2
m.groupdict([default=None])→ dict: name→subgroup: all named
6a 6b 6c
subgroups of the match - default give access to subgroups not in the key nl_langinfo() value usage key meaning
match D_FMT usable as format for strftime() for date numbers.
m.start([group=0])→ int: index of start of substring matched by group, T_FMT usable as format for strftime() for time 1
Possible values : 0=currency and value surrounded by
-1 if group exists but not in match T_FMT_AMPM usable as format for strftime() for time in parentheses, 1=sign should precede value and currency symbol,
m.end([group=0])→ int: index of end of substring matched by group, -1 if am/pm format 2=sign should follow value and currency symbol, 3=sign should
group exists but not in match DAY_1…DAY_7 name of the nth day of the week - first day is immediately precede value, 4=sign should immediately follow
m.span([group=0])→ (int{2}): values of start and end methods for the sunday value, LC_MAX=nothing specified in this locale.
group
ABDAY_1… abbreviated name of the nth day of the week - Multilingual Support
m.pos → int: pos value of search/match method ABDAY_7 first day is sunday
m.endpos → int: endpos value of search/match method Standard module gettext for internationalization (I18N) and
MON_1… MON_12 name of the nth month
m.lastindex → int/None: index of last matched capturing group localization (L10N) services - based on GNU gettext API + higher
m.lastgroup → string/None: name of last matched capturng group ABMON_1… abbreviated name of the nth month interface. See docs for explanations about tools usage.
ABMON_12
m.re → RE_Pattern: pattern used to produce match object Base API
RADIXCHAR radix character (decimal dot/comma/…)
m.string → string: string used in match/search to produce match object
THOUSEP separator character for thousands bindtextdomain(domain[,localedir])→ str: bounded directory - bind
1
Back references extended to \g<groupnum> and \g<groupname>. domain to localedir directory if specified (used when searching for .mo
1 YESEXPR regular expression (of C library!) usable for yes
Using part of string between pos and endpos. files)
Group number 0 correspond to entire matching. reply bind_textdomain_codeset(domain[,codeset])→ codeset binding: bind
NOEXPR regular expression (of C library!) usable for no domain to codeset if specified - change xxgettext() returned strings
Localization reply encoding
Standard module locale provide posix locale service (internationa- CRNCYSTR currency symbol, preceded by - if should appear textdomain([domain])→ global domain: set global domain if specified
lization). before the value, by + if should appear after the and not None
setlocale(category[,locale]) → current/new settings: if locale specified value, by . if should replace radix character gettext(message)→ string: localized translation of message - based on
(as string or as tuple(language code, encoding)) then modify locale ERA era - generally not defined - same as E format in
settings for category and return new one - if locale not specified or None, current global domain, language, and locale directory - usually aliased as _
strftime() in local namespace
return current locale - not thread safe ERA_YEAR year in era lgettext(message)→ string: like gettext(), using preferred encoding
localeconv()→ dict: database of local conventions
ERA_D_T_FMT usable as format for strftime() for date and dgettext(domain,message)→ string: like gettext(), looking in
nl_langinfo(option)→ string: locale-specific informations - not available
time with era specified domain.
on all systems - options may vary on systems - see options p7
ERA_D_FMT usable as format for strftime() for date with ldgettext(domain,message)→ string: like dgettext(), using preferred
getdefaultlocale([envvars])→(language code, encoding): try to
era encoding
determine default locale settings
ALT_DIGITS up to 100 values representing 0 to 99 ngettext(singular,plural,n)→ string: like gettext(), but consider plural
getlocale([category])→ current LC_* setting for category - category
forms (see Python and GNU gettext docs)
default to LC_CTYPE - for language code and ancoding it may be None localeconv keys lngettext(singular,plural,n)→ string: like ngettext(), using preferred
getpreferredencoding([do_setlocale])→ str: user preffered encoding
key meaning encoding
for text data - set do_setlocale to False to avoid possible call to currency_symbol Local currency symbol for monetary values. dngettext(domain,singular,plural,n)→ string: like ngettext(), looking
setlocale()
decimal_point Decimal point character for numbers. in specified domain.
normalize(localename)→ normalized locale code for localename - usable
frac_digits Number of fractional digits used in local ldngettext(domain,singular,plural,n)→ string: like dngettext(),
with setlocale() - return localename if normalization fails
formatting of monetary values. using preferred encoding
resetlocale([category]) ➤ reset locale for category to default setting - Generally _ is bound to gettext.gettext, and translatable strings
grouping [int]: relative positions of 'thousands_sep'
category default to LC_ALL are written in sources using _('thestring'). See docs for usage
in numbers. CHAR_MAX at the end stop
strcoll(s1,s2)→ int: compare two strings - follow LC_COLLATE setting examples.
grouping. 0 at the end repeat last group.
- return 0 if s1==s2, <0 if s1<s2, >0 if s1>s2
int_curr_symbol International currency symbol of monetary Class based API
strxfrm(string)→ string:transform string for locale-aware comparison
values.
format(format,val[,grouping])→ string:convert val float using format (% The recommended way. Module gettext defines a class
int_frac_digits Number of fractional digits used in Translations, dealing with .mo translation files and supporting
operator conventions) - follow LC_NUMERIC settings (decimal point, +
international formatting of monetary
grouping if it is true) str/unicode strings.
values.
str(float)→ string: convert float - follow LC_NUMERIC settings (decimal find(domain[,localedir[,languages[,all]]])→ str/None: .mo file name
mon_decimal_point Decimal point used for monetary values.
point) for translations (search in localedir/language/LC_MESSAGES/domain.mo)
atof(string)→ float: convert string to float - follow LC_NUMERIC settings
mon_grouping Equivalent to 'grouping', used for monetary translation(domain[,localedir[,languages[,class_[,fallback[,codeset]
values.
atoi(string)→ int: convert string to integer - follow LC_NUMERIC settings ]]]])→Translations: object from class class_ (default to
mon_thousands_sep Group separator used for monetary values.
CHAR_MAX → symbolic constant used by localeconv() GNUTranslations, constructor take file object as parameter) - if true
n_cs_precedes True if currency symbol preceed negative
Categories fallback allow to return a NullTranslations if no .mo file is found,
monetary values, false if it follow.
default to false (raise IOError) - codeset change charset used to encode
LC_CTYPE → character type - case change behaviour n_sep_by_space True if there is a space between currency
translated strings
LC_COLLATE → strings sorting - strcoll() and strxfrm() functions symbol and negative monetary value.
install(domain[,localedir[,unicode[,codeset]]]) ➤ install _ function in
LC_TIME → time formating - time.strftime() n_sign_posn Position of negative sign for monetary Python's builtin namespace, to use _('thestring')
LC_MONETARY → monetary values formating - options from localeconv() values1.
LC_MESSAGES → messages display - os.strerror() - not for Python negative_sign Symbol used to annotate a negative Null Translations
messages monetary value. The NullTranslations is a base class for all Translations.
LC_NUMERIC → numbers formatting - format(), atoi(), atof() and p_cs_precedes True if currency symbol preceed positive t.__init__([fp]) ➤ initialize translations: fp is a file object - call
str() of this module (dont modify normal Python number formating) monetary values, false if it follow. _parse(fp) if it is not None
LC_ALL → all locales - used to change/retrieve the locale for all categories p_sep_by_space True if there is a space between currency t._parse(fp) ➤ nothing: subclasses override to read data from the file
symbol and positive monetary value. t.add_fallback(fallback) ➤ add fallback used if cannot found
nl_langinfo options
p_sign_posn Position of positive sign for monetary translation for a message
key nl_langinfo() value usage values1. Define methods gettext, lgettext, ngettext, lngettext as in the
CODESET name of character encoding positive_sign Symbol used to annotate a positive base API. And define speciale methods ugettext and ungettext
D_T_FMT usable as format for strftime() for time and monetary value. returning unicode strings (other forms return encoded str strings).
date thousands_sep Character used between groups of digits in
7a 7b 7c
Return translated message, forwarding to fallback if it is defined. Unless using a sequence as a mapping key, or ensuring it is seq.insert(index,item) ➤ item inserted at index
Overriden in subclasses. immutable data, prefer list to tuple. seq.remove(expr) ➤ remove first expr item from sequence
t.info()→ return protected _info attribute 1
Use in place of range to avoid building huge lists just for indexing. seq.pop([index]) → item: remove and return item at index (default -1)
t.charset()→ return protected _charset attribute Operations on Sequences seq.reverse() ➤ items reversed in place
t.output_charset()→ return protected _output_charset attribute seq.sort([cmp][,key][,reverse]) ➤ items sorted in place - cmp :
See Operations on Containers (p8) too.
(defining encoding used to return translated messages) seq1 + seq2 → concatenation of seq1 and seq2 custom comparison fct(a,b), retval <0 or = 0 or >0 - key : name of items
t.set_output_charset(charset) ➤ set _output_charset attribute attribute to compare - reverse : bool
sequence * n → concatenation of sequence duplicated n times
t.install([unicode]) ➤ bind _ in builtin namespace to del seq[index] ➤ remove item from sequence
n * sequence → concatenation of sequence duplicated n times
self.gettext() or self.ugettext() upon unicode (default to false) del seq[start:stop[:step]] ➤ remove items from sequence
reversed(sequence)→ iterator throught sequence in reverse order
GNU Translations sorted(sequence[,cmp[,key[,reverse]]])→ list: new list, sorted items Overriding Sequences Operations
The GNUTranslations class (subclass of NullTranslations) is from iterable - see list.sorted() __getitem__(self,index2)→ value: item at index, called for
based on GNU gettext and .mo files. filter1(fct,sequence)→ list: new list where fct(item) is True. Use None self[index]
Messages ids and texts are coerced to unicode. fct for a boolean test on items __setitem__1(self,index2,value) ➤ set item at index to value, called
Protected _info attribute contains message translations. map1(fct,sequence,…)→ list: new list where ith item is fct(ith items of for self[index]=value
Translation for empty string return meta-data (see doc). sequence(s)) __delitem__1(self,index2) ➤ remove item at index, called for
Define methods gettext, lgettext, ugettext, ngettext, reduce(fct,sequence[,initializer])→ value: fct applied cumulatively to del self[index]
lngettext, ungettext as in NullTranslations interface - same sequence items, f(f(…f(f(f(initializer,a),b),c,…) 1
Only for mutable sequences.
rules for return values (str/unicode). Message translations are zip1(sequence,…)→ list: list of tuples, ith tuple contains ith items of each 2
Parameter index can be a slice [start,stop,step] - replace old
searched in catalog, then in fallback if defined, and if no translation sequences __getslice__, __setslice__, __delslice__.
is found, message itself is returned (for n… methods, return 1
See Iteration Tools (p9) as replacement (avoid creating a new Can also override arithmetic operations __add__ (concatenation )
singular forms if n=1 else plural forms). list). and __mul__ (repetition ), container operations and object
operations.
CONTAINERS Indexing
BULK
Tools
Batteries included: pdb (Python debugger), code bench with timeit
(p10).
A must have: pychecker.
Take a look: pylint, psyco, pyrex, pycount, trace2html,
depgraph, coverage, pycover, Pyflakes, pyreverse, HAP.
Links
Docs: http://www.python.org/doc/
FAQ Python: http://www.python.org/doc/faq/
PEPs: http://www.python.org/dev/peps/ (Python Enhancement
Proposal)
HOWTOs: http://www.amk.ca/python/howto/
Cookbook: http://aspn.activestate.com/ASPN/Python/Cookbook/
Dive Into: http://www.diveintopython.org/