Python 2.4 Quick Reference Card

 
 
Python 2.4 Quick Reference Card                                                                                               Styles : keyword function/method type replaced_expression variable               Types
                                                                                                                                                                                                                          basestring1 bool buffer complex dict exception file float
                 ©2005-2007 — Laurent Pointal — License CC [by nc sa]                                                                         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.
Builtins.................................................... 1            Operations on Sequences..........................8
                                                                                                                                             PYTHONCASEOK           1
                                                                                                                                                                        no case distinction in module→file mapping         __import__ abs apply1 callable chr classmethod cmp coerce
   Types......................................................... 1       Indexing.....................................................8
   Functions................................................... 1         Operations on mutable sequences............ 8                      PYTHONDEBUG            1
                                                                                                                                                                        = -d command-line option                           compile delattr dir divmod enumerate eval execfile filter
Statements..............................................1                 Overriding Sequences Operations............. 8                     PYTHONHOME              Modify standard Python libs prefix and exec prefix    getattr globals hasattr hash help hex id input intern2
   Blocks........................................................ 1    Mappings (dictionaries)........................... 8                                            locations. Use [:].             isinstance issubclass iter len locals map max min oct open
   Assignment Shortcuts................................1                  Operations on Mappings............................ 8               PYTHONINSPECT           1
                                                                                                                                                                        = -i command-line option                           ord pow property range raw_input reduce reload repr reversed
Console & Interactive Input/Output.........1                              Overriding Mapping Operations.................8                                                                                                  round setattr sorted staticmethod sum super unichr vars zip
Objects, Names and Namespaces........... 2                                Other Mappings......................................... 8          PYTHONOPTIMIZE          1
                                                                                                                                                                        = -O command-line option                           1
                                                                                                                                             PYTHONPATH              Directories where Python search when importing          Use f(*args,**kargs) in place of apply(f,args,kargs).
   Identifiers...................................................2     Sets......................................................... 8                                                                                     2
   Objects and Names, Reference Counting.. 2                              Operations on Sets.................................... 8                                     modules/packages. Separator : (posix) or ;            Don't use intern.
   Mutable/Immutable Objects.......................2                   Other Containers Structures, Algorithms 9                                                       (windows). Under windows use registry              STATEMENTS
   Namespaces.............................................. 2             Array..........................................................9                             HKLM\Sofware\….
   Constants, Enumerations...........................2                    Queue........................................................ 9    PYTHONSTARTUP           File to load at begining of interactive sessions.    One statement per line1. Can continue on next line if an expression or a
Flow Control............................................ 2                Priority Queues.......................................... 9                                                                                      string is not finished ( ( [ { """ ''' not closed), or with a \ at end of
   Condition....................................................2         Sorted List..................................................9
                                                                                                                                             PYTHONUNBUFFERED 1 = -u command-line option
   Loop...........................................................2       Iteration Tools............................................9       PYTHONVERBOSE           1
                                                                                                                                                                        = -v command-line option                           line.
   Functions/methods exit............................. 2               Date & Time............................................ 9
                                                                                                                                              1
                                                                                                                                                If set to non-empty value.                                                Char # start comments up to end of line.
   Exceptions................................................. 2          Module time...............................................9                                                                                     pass                              Null statement.
   Iterable Protocol.........................................2            Module datetime........................................9           COMMAND-LINE OPTIONS                                                         assert expr[,message]             Assertion check expression true.
Interpretation / Execution....................... 2                       Module timeit.............................................9
Functions Definitions & Usage................ 2                           Other Modules......................................... 10
                                                                                                                                             python [-dEhiOQStuUvVWx] [-c cmd | -m mod | file | -] [args]                 del name[,…]                      Remove name → object binding.
   Parameters / Return value.........................2                 Files.......................................................10        -d       Output debugging infos from parser.                                 print [>>obj,][expr[,…][,]        Write expr to sys.stdout2.
   Lambda functions...................................... 2               File Objects.............................................. 10      -E       Ignore environment variables.                                       exec expr [in globals [, locals]] Execute expr in namespaces.
   Callable Objects.........................................2             Low-level Files......................................... 10        -h       Print help and exit.                                                fct([expr[,…]],[name=expr[,…]] Call any callable object fct with given
   Calling Functions........................................2             Pipes........................................................ 10   -i       Force interactive mode with prompt (even after script
   Functions Control.......................................2              In-memory Files....................................... 10                                                                                        [,*args][,**kwargs])              arguments (see Functions Definitions &
                                                                                                                                                      execution).                                                                                            Usage - p2).
   Decorators................................................. 2          Files Informations.................................... 10
Types/Classes & Objects......................... 3                        Terminal Operations................................ 11
                                                                                                                                             -O       Optimize generated bytecode, remove assert checks.                  name[,…] = expr                   Assignment operator3.
   Class Definition..........................................3            Temporary Files....................................... 11          -OO      As -O and remove documentation strings.                             1
   Object Creation..........................................3             Path Manipulations.................................. 11            -Q arg   Division option, arg in [old(default),warn,warnall,new].               Multiple statements on same line using ; separator - avoid if not
   Classes & Objects Relations.......................3                    Directories............................................... 11      -S       Don't import site.py definitions module.                             necessary.
                                                                                                                                                                                                                           2
   Attributes Manipulation............................. 3                 Special Files.............................................11       -t       Warn inconsistent tab/space usage (-tt exit with error).               Write to any specified object following file interface (write method).
   Special Methods.........................................3              Copying, Moving, Removing.................... 11                                                                                                 Write space between expressions, line-return at end of line except with
                                                                                                                                             -u       Use unbuffered binary output for stdout and stderr.
   Descriptors protocol...................................3               Encoded Files...........................................11                                                                                       a final ,.
   Copying Objects.........................................3              Serialization............................................. 12      -U       Force use of unicode literals for strings.
                                                                                                                                                                                                                           3
   Introspection..............................................3           Persistence.............................................. 12       -v       Trace imports.                                                         Left part name can be container expression. If expr is a sequence of
Modules and Packages............................ 3                        Configuration Files...................................12           -V       Print version number and exit.                                       multiple values, can unpack into multiple names. Can have multiple
   Source encodings...................................... 3            Exceptions.............................................12             -W arg   Emit warning for arg "action:message:category:module:lineno"         assignments of same value on same line : a = b = c = expr.
   Special Attributes.......................................3             Standard Exception Classes.....................12                  -x       Skip first line of source (fort non-Unix forms of #!cmd).           Other statements (loops, conditions…) introduced in respective parts.
Main Execution / Script Parameters........ 3                              Warnings..................................................12
                                                                                                                                             -c cmd   Execute cmd.                                                             Blocks
Operators................................................ 4               Exceptions Processing............................. 12
   Priority....................................................... 4   Encoding - Decoding............................. 12                   -m mod   Search module mod in sys.path and runs it as main script.           A : between statements defines dependant statements, written on same
   Arithmetic Operators................................. 4             Threads & Synchronization................... 12                       file     Python script file to execute.                                       line or written on following line(s) with deeper indentation.
   Comparison Operators...............................4                   Threading Functions................................ 12             args     Command-line arguments for cmd/file, available in                   Blocks of statements are simply lines at same indentation level.
   Operators as Functions..............................4                  Threads....................................................13               sys.argv[1:].                                                           if xpi/4 :
Numbers..................................................4                Events......................................................13     FILES EXTENSIONS                                                                      a = pi/2
   Operators...................................................4          Semaphores.............................................13
   Functions................................................... 4         Condition Variables..................................13            .py=source, .pyc=bytecode, .pyo=bytecode optimized, .pyd=binary                       b = -pi/2
Bit Level Operations................................ 5                    Synchronized Queues.............................. 13               module, .dll/.so=dynamic library.                                                else :
   Operators...................................................5       Process..................................................13           .pyw=source associated to pythonw.exe on Windows platform, to run                     a = asin(v)
Strings..................................................... 5            Current Process....................................... 13          without opening a console.                                                            b = pi/2-a
   Escape sequences..................................... 5                Signal Handling........................................14
                                                                                                                                                                                                                           Statement continuation lines don't care indentation.
   Unicode strings..........................................5             Simple External Process Control..............14                    LANGUAGE KEYWORDS                                                             To avoid problems, configure your editor to use 4 spaces in place of
   Methods and Functions..............................5                   Advanced External Process Control......... 14
   Formating.................................................. 5       XML Processing..................................... 15                List of keywords in standard module keyword.                                  tabs.
   Constants...................................................6          SAX - Event-driven...................................15            and as1 assert break class continue def del elif else except                     Assignment Shortcuts
   Regular Expressions.................................. 6                DOM - In-memory Tree............................ 16                exec finally for from global if import in is lambda not or
   Localization................................................6       Databases............................................. 17                                                                                          a += b      a -= b       a *= b              a /= b
                                                                                                                                             pass print raise return try while yield
   Multilingual Support...................................7               Generic access to DBM-style DBs............ 17                     1                                                                            a //= b     a %= b       a **= b
Containers............................................... 7               Standard DB API for SQL databases........ 17                         not reserved, but avoid to redefine it.
                                                                                                                                                                                                                          a &= b      a |= b       a ^= b              a >>= b        a
input([prompt]) → evaluation of user input (typed data)                      methods).                                                                              Generators
raw_input([prompt]) → str: user input as a raw string                        Namespaces can be nested, inner namespaces hidding identical names              Functions retaining their state between two calls. Return values using
Direct manipulation (redefinition) of stdin/stdout/stderr via sys module :    from outer namespaces.                                                          yield. Stop generation via simple return or via raise StopIteration.
sys.stdin               sys.stdout           sys.stderr                      dir([object]) → list: names defined in object namespace1                          1) build generator from function : gen=generatorfct(args)
sys.__stdin__           sys.__stdout__       sys.__stderr__                  vars([object]) → dict2: identifier:value of object as a namespace1                2) use gen.next() values until StopIteration is raised.
 All are files or files-like objects. The __xxx__ forms keep access to        1
                                                                                if object not specified use nearest namespace (locals).
 original standard IO streams.                                                2
                                                                                                                                                             Generator iterable expressions with : (x for x in iterable where cond)
                                                                                must not be modified.
Ctrl-C raises KeyboardInterrupt exception.                                                                                                                          Operations with/on Iterable
                                                                                  Constants, Enumerations
_ → value of last expression evaluation
help([object]) ➤ print online documentation                                  Use uppercase and _ for constants identifiers (good practice). May define       See Operations on Containers (p7).
sys.displayhook → (rw) fct(value) called to display value                     namespaces to group constants. Cannot avoid global/local name                  See Iteration Tools (p9).
                                                                              redefinition (can eventually define namespaces as classes with
sys.__displayhook__ → backup of original displayhook function
sys.ps1 → str: primary interpreter prompt
                                                                              attributes access control - not in Python spirit, and execution cost).         INTERPRETATION / EXECUTION
                                                                             See third party modules pyenum for strict enum-like namespace.
sys.ps2 → str: secondary (continuation) interpreter prompt                                                                                                   compile(string1,filename,kind2[,flags3[,dont_inherit3]]) → code object
See external package ipython for an enhanced interactive Python shell.       FLOW CONTROL                                                                    eval(expression[,globals[,locals]]) → value: evaluation4 of expression string
                                                                                                                                                             eval(code_object[,globals[,locals]]) → value: evaluation4 of code_object
OBJECTS, NAMES        AND   NAMESPACES                                       Condition                       Loop                                            exec5 statements [in globals[,locals]] ➤ statements string1 executed4
                                                                               if cond : inst                  for var[,…] in iterable : inst                execfile(filename[,globals[,locals]]) ➤ file filename interpreted4
   Identifiers                                                               [ elif cond : inst ]                                                             1
                                                                                                             [ else : inst ]                                    Multi-line statements in source code must use \n as newline, and must
Use : [a-zA-Z_][a-zA-Z0-9_]*                                                 [ else : inst ]
                                                                                                               while cond : inst                              be terminated by a newline.
Special usage for underscore :                                                                                                                                2
                                                                             There is no 'switch' or 'case'. [ else : inst ]                                    Kind relative to string content, 'exec' → sequence of statements,
   _xxx         global not imported by import *
                                                                             Can use if elif elif… else.                                                      'eval' → single expression, 'single' → single interactive statement.
   _xxx         implementation detail, for internal use (good practice)                                      Exit loop with break.
                                                                             Can use a mapping with                                                           3
                                                                                                                                                                Flags and dont_inherit are for future statements (see doc).
   __xxx        'private' class members, defined as _ClassName__xxx                                          Go to next iteration with continue.
                                                                             functions bound to cases.                                                        4
                                                                                                                                                                In context of globals and locals namespaces.
   __xxx__ normally reserved by Python                                                                                                                        5
                                                                                                              Loops else blocs only executed when               Exec is a langage statement, others are builtin functions.
Case is significant : This_Name != THIS_NAME.
                                                                                                              loop exit normally (without break).
    Objects and Names, Reference Counting                                                                                                                    FUNCTIONS DEFINITIONS & USAGE
                                                                                 Functions/methods exit
Data are typed objects (all data), names are dynamically bound to                                                                                            def fctname([paramname[=defaultvalue][,…]] [,*args][,**kwargs]) :
 objects.                                                                    Exit function/method with return [value]                                             instructions
= assignment statement bind result of right part evaluation into left part   Exit from generator body with yield value                                       new.function(code,globals[,name[,argdefs]]) → python function (see docs)
 name(s)/container(s). Examples :                                             Multiple returned values using tuple data.
                                                                              Cannot yield within a try/finally block.                                            Parameters / Return value
a = 3*c+5      a,b = ("Hello","World")         x,y,tabz[i] = fct(i)
s = "Hello" pi,e = 3.14,2.71                   a,b = b,a                                                                                                     Parameters are passed by references to objects.
                                                                                 Exceptions                                                                   You can modify values of mutable objects types.
When an object is no longer referenced (by names or by containers), it is     try : inst                                                                      You cannot modify values of immutable objects types - as if they were
destroyed (its __del__ method is then called).                                except [ except_class [,value ]] : inst                                         passed by value.
sys.getrefcount(object)→ int: current reference counter of object             …                                                                              Notation * → variable list of anonymous parameters in a tuple.
                                                                             [ else : inst ]                                                                 Notation ** → variable list of named parameters in a dict.
Standard module weakref define tools to allow objects to be garbage           Can have a tuple of classes for except_class. Not specifying a class           Return value(s) with return [value[,…]]
collected when necessary and dynamically re-created on-demand.                catch all exceptions.                                                          For multiple values, return a tuple. If no return value specified or if end
    Mutable/Immutable Objects                                                 Block else executed when try block exit normally.                               of function definition reached, return None value.
Mutable objects can be modified in place. Immutable objects cannot be        try : inst                                                                          Lambda functions
 modified (must build a new object with new value).                          finally : inst
Immutable : bool, int, long, float, complex, string, unicode, tuple,                                                                                         lambda param[,…] : expression
 frozenset, buffer, slice.                                                   Process finally block in all execution paths (normal or exception).             Anonymous functions defined inline. Result of expression evaluation is
                                                                             raise exception_class[,value[,traceback]]                                        returned (it must be an expression, no loop, no condition).
Mutable : list, set, dict and other high level class objects.
                                                                             raise exception_object                                                           Expression uses values known at definition time (except for params).
There is no constant definition. Just use uppercase names to identify
                                                                             raise                                                                               Callable Objects
 symbols which must not be modified.
                                                                             Last form re-raise the currently catched exception in an exception              Objects having a __call__ method can be used as functions.
    Namespaces                                                               handler.
                                                                                                                                                             Methods bound to objects can be used as functions : f = o.meth
Places where Python found names.
                                                                                 Iterable Protocol                                                           callable(x) → bool: test x callable with x(…)
Builtins namespace → names from module __builtins__, already
                                                                             Generic and simple protocol allowing to iterate on any collection of data.          Calling Functions
 available.
Global namespace → names defined at module level (zero indentation).         Objects of class defining __iter__ or __getitem__ are iterable (directly
                                                                                                                                                             [name=] fctname([expr[,…]][,name=expr[,…][,*args][,**args])
Local namespace → names defined in methods/functions.                         usable in for loops).
                                                                                                                                                             Anonymous parameters passed in parameters order declaration.
                                                                             __iter__(self) → iterator on self
del name ➤ remove existing name from namespace (remove object binding)                                                                                       Params having default value can be omitted.
                                                                             iter(object) → iterator on iterable object
globals() → dict: identifier→value of global namespace                                                                                                       Notation * → pass variable list of anonymous parameters in a tuple.
                                                                             iter(callable,sentinel) → iterator returning callable() values up to sentinel
locals() → dict: identifier→value of local namespace                                                                                                         Notation ** → pass variable list of named parameters in a dict.
                                                                             enumerate(iterable)→ iterator returning tuples (index,value) from iterable
Current scope → names directly usable. Searched in locals, then locals                                                                                          Functions Control
                                                                                    Iterators Objects Interface
 from enclosing definitions, then globals, then builtins.                                                                                                    sys.getrecursionlimit()→ int: current recursion limit for functions
Out-of-scope name → use the dotted attribute notation x.y (maybe             next(self)→ next item1                                                          sys.setrecursionlimit(limit) ➤ set recursion limit for functions
 x.y.z.t)… where x is a name visible within the current scope.               __iter__(self)→ iterator object itself
                                                                              1                                                                                  Decorators
                                                                                When reach end of collection, raise StopIteration exception on
Class namespace → names defined in a class (class members).                                                                                                  Glue code (functions) called at functions and methods definitions time,
                                                                              subsequent calls (ie. iterator usable only one time on a collection).
Object namespace → names usable with object.name notation (attributes,                                                                                        return the final function/method (generally with wrapping code).

                                    2a                                                                              2b                                                                            2c
@decoratorname [(decorator_arguments)] […]                                   1
                                                                               If don't return a classref object, then object.__init__ is called with           Example of Introspection Attributes
def fct(fct_rguments):…                                                      initargs.                                                                    Note: classes are objects too!
@dec1 @dec2(args) @dec3                def fct(…):…                                 Object Cast                                                          __base__ → list: parent classes of a class
def fct(…):…                    like   fct = dec1(dec2(args)(dec3(fct))))    __repr__(self)→ str: called for repr(self) and `self`                       __slots__ → tuple: allowed objects attributes names1 of a class
                            ➤                                                __str__(self) → str: called for str(self) and print self                    __class__ → class/type: object's class
See page PythonDecoratorLibrary in python.org Wiki for some                                                                                              __dict__ → dict: defined attributes (object namespace) of an instance
                                                                             __coerce__(self,other) → value, called for coerce(self,other)
decorators definitions.                                                                                                                                  __doc__ → string: documentation string of a package, module, class, function
                                                                                    Object Hash Key                                                      __name__ → str: object definition name of a function
TYPES/CLASSES & OBJECTS                                                      __hash__(self)→ int: 32 bits hash code for object, used for hash(obj)and    __file__ → string: pathname of loaded module .pyc, .pyo or .pyd
All data are typed objects relying to classes.                                quick dict mapping keys comparison - default implementation use             1
                                                                                                                                                            List of allowed attributes names. Usage discouraged.
type(o) → type: type object of o                                              hash(id(self))
Standard module types define type objects for builtins types.
                                                                                    Attributes access
      Class Definition
                                                                                                                                                         MODULES       AND   PACKAGES
                                                                              See also "Descriptors protocol" infra.
class classname [(parentclass[,…])] :                                                                                                                    File gabuzo.py ➤ module gabuzo.
                                                                             __getattr__(self,name)→ value, called for undefined attributes
        varname = expr ➤ varname defined in classname namespace                                                                                          Directory kramed/ with a file __init__.py ➤ package kramed.
                                                                             __getattribute__(self, name)→ value, always called
        def metname(self[,…]): ➤ define methods like functions                                                                                           Can have sub-packages (subdirectories having __init__.py file).
                                                                             __setattr__(self, name, value) ➤ called for obj.name=value
Support multiple inheritance. Can inherit from builtin class.                                                                                            Searched in the Python PATH.
                                                                             __delattr__(self, name) ➤ called for del obj.name
Inherit at least from object base class => Python 'new style class'.                                                                                     Current Python PATH stored in sys.path list. Contains directories and
                                                                             __call__(self, *args, **kwargs)→ value, called for obj(…)
First parameter of methods is target object, standard use self name.                                                                                     .zip files paths. Built from location of standard Python modules,
                                                                                    Static method / Class method                                         PYTHONPATH environment variable, directory of main module given on
Access class members via class name, object members via self.
                                                                             Use standard decorators (see Decorators p2).                                command line, data specified in lines of .pth files found in Python home
 This doc consider you use new style class (inheriting from object).
                                                                             class ClassName :                                                           directory, and data specified in registry under Windows.
new.classobj(name,baseclasses,dict) → new class (see docs)
                                                                                 @staticmethod                                                           Current list of loaded modules stored in sys.modules map (main module
new.instancemethod(fct,instance,class) → new method: bound to instance
                                                                                 def methodname(…): …                                                     is under key __main__).
 it it is not None, see docs
                                                                                 @classmethod                                                            import module [as alias] [,…]
       Metaclass                                                                 def methodname(classref,…): …                                           from module import name [as alias] [,…]
Class definition create a new type. It can be done 'by hand' with :                                                                                      from module import *
                                                                                  Descriptors protocol
x = type('classname',(parentclass,[…]),{varname:expr[,…]}                                                                                                reload(module) ➤ module is reloaded (but existing references still refer old
                                                                             Descriptors are attribute objects controling access to attributes values.
 def metname(self[,…]):                                                                                                                                   module content)
                                                                              They must define some of following methods :                               new.module(name[,doc]) → new module object.
x.metname = metname                                                          __get__(self,obj,ownerclass)→ attribute value for obj
This allow creation of metaclass class (class building other class).                                                                                      Import can use package path (ex:from encoding.aliases import…).
                                                                             __set__(self,obj,value) ➤ modify attribute in obj, set to value
                                                                                                                                                          Direct import from a package use definitions from __init__.py file.
     Object Creation                                                         __delete__(self,obj) ➤ remove attribute from obj                             Very careful with import * as imported names override names already
obj = ClassName(initargs…)                                                   In these methods self is the descriptor object, and obj is the target        defined.
 In case of exception during initialization, object is destroyed when         object which attribute is manipulated.                                      To limit your modules names exported and visible by import *, define
 exiting init code (reference counter reach zero).                                  Properties                                                            module global __all__ with list of exported names (or use global
new.instance(class[,dict]) → object: create new class instance without
                                                                             A descriptor to directly bind methods/functions to control attribute         names _xxx).
 calling __init__ method, dict is initial object attributes
                                                                              access. Use builtin type property with init args.                          See __import__ builtin function, and modules imp, ihooks.
    Classes & Objects Relations                                              class MyClass :                                                             __import__(modulename[, globals[,locals[,lnameslist]]])
isinstance(obj,classinfo) → bool: test object kind of type/class classinfo      attributename = property(getter,setter,deleter,description)                    Source encodings
issubclass(aclass,aparent) → bool: test same class or parent relationship     Each init arg default to None (ie. undefined).                             See PEP 263. Declare source files encoding in first or second line in a
 Prefer isinstance() to type() for type checking.                                                                                                         special comment.
                                                                                 Copying Objects
Parent class methods are not automatically called if overriden in            Assignment only duplicate references. To shallow copy an object (build a    # -*- coding: encoding_name -*-
 subclass - they must be explicitly called if necessary.                      new one with same values - referencing same content), or to deep copy      If this is not specified, Python use sys.getdefaultencoding() value
Call parent methods via super function :                                      an object (deep-copying referenced content), see object copy methods,       (see modules sitecustomize.py and user.py).
   super(ThisClass,self).methodname(self,args…)                               and functions in standard module copy.                                       It is important to specify encoding of your modules as u"…" strings use
Or the old way, via parent class namespace :                                 copy.copy(object)→ value: shallow copy of object                              it to correctly build unicode literals.
   ParentClass.methodname(self,args…)                                        copy.deepcopy(object[[,memo],_nil])→ value: deep copy of object1               Special Attributes
                                                                              1
    Attributes Manipulation                                                     Params memo and nil are used in recursive deepcopy, their default        __name__ → str: module name, '__main__' for command-line called script
object.name = value                                                           values are None and empty list.                                            __file__ → string: pathname of compiled module loaded
setattr(object,name,value) ➤ object attribute set to value                          Copy Protocol
object.name → value of object attribute
                                                                                                                                                         MAIN EXECUTION / SCRIPT PARAMETERS
                                                                             __copy__(self)→ value: shallow copy of self, called by copy.copy(…)
getattr(object,name[,default])→ value of object attribute                                                                                                The 'main' module is the module called via command-line (or executed
                                                                             __deepcopy__(self,memo)→ value: deep copy of self, called by
del object.name                                                                                                                                           by shell with first script line #! /bin/env python).
                                                                              copy.deepcopy(…)
delattr(object,name) ➤ object attribute removed                                                                                                          Command-line parameters are available in sys.argv (a python list).
                                                                              For copying, objects can define pickling protocol too (see Files -
                                                                                                                                                         At end of module, we may have :
   Special Methods                                                            Serialization - p12), in place of __copy__ and __deepcopy__.               if __name__=='__main__' :
Other special overridable __xxx___ methods are listed in respective              Introspection                                                                # main code
sections.                                                                                                                                                     # generally call a 'main' function:
                                                                             Beyond this documentation. Many __xxx___ attributes are defined, some
       Object Life                                                            are writable (see other docs).                                                  mainfunction(sys.argv[1:])
                                                                             See standard module inspect to manipulate these data.                            # or in lib modules, execute test/demo code...
__new__(classref,initargs…)→ object of classref type, already initialized1
__init__ (self,initargs…)➤ called to initialize object with initargs                                                                                     Execution exit after last main module instruction (in multithread, wait
__del__ (self)➤ called when object will be destroyed                                                                                                      also for end of non-daemon threads), unless interactive mode is forced.

                                       3a                                                                           3b                                                                       3c
Can force exit with calling sys.exit(code), which raise a SystemExit         Operators as Functions                                              long(expr[,base=10]) → long: cast of expr
 exception - see Current Process - Exiting (p13).                         Operators are also defined as functions in standard operator module.   Builtin floating point types : float (like C double), complex (real and
                                                                                                                                                  imaginary parts are float).
OPERATORS                                                                        Comparison
                                                                                                                                                 float(expr) → float: representation of expr
Deal with arithmetic, boolean logic, bit level, indexing and slicing.     lt(a,b) = __lt__(a,b)                 ne(a,b) = __ne__(a,b)            complex(x[,y]) → complex: number: x+yj
                                                                          le(a,b) = __le__(a,b)                 ge(a,b) = __ge__(a,b)            [x+]yj → complex: number, ex: 3+4j -8.2j
    Priority
                                                                          eq(a,b) = __eq__(a,b)                 gt(a,b) = __gt__(a,b)            c.real → float: real part of complex number
 1 (a,…) [a,…]        6 x+y      11 x=y x==y x!=y
                                                                                 Logical / Boolean                                               c.img → float: imaginary part of complex number
   {a:b,…} `…`          x-y          xy x is y x is not y x in s
                                                                          not_(o) = __not__(o)                  and_(a,b) = __and__(a,b)         c.conjugate() → complex: conjugate of complex number (real,-img)
                                     x not in s
                                                                          truth(o)                              or_(a,b) = __or__(a,b)            Maximum int integer in sys.maxint.
 2 s[i] s[i:j]        7 xy                                              is_(a,b)                              xor(a,b) = __xor__(a,b)
   s.attr f(…)                                                                                                                                    Automatic conversions from int to long when result overflow max int.
                                                                          is_not(a,b)
 3 +x -x ~x           8 x&y      13 x and y                                                                                                       Direct conversions from/to strings from/to int, long… via types
                                                                                 Arithmetic                                                       constructors.
 4 x**y               9 x^y      14 x or y
                                                                          abs(o) =   __abs__(o)            truediv(a,b) = __truediv__(a,b)       Type Decimal defined in standard module decimal.
 5 x*y x/y x%y       10 x|y      15 lambda args:expr                                                                                             Base fixed type compact storage arrays in standard module array.
                                                                          add(a,b)   = __add__(a,b)        floordiv(a,b) = __floordiv__(a,b)
   Arithmetic Operators                                                   sub(a,b)   = __sub__(a,b)        neg(o) = __neg__(o)                        Operators
Can be defined for any data type.                                         mul(a,b)   = __mul__(a,b)        pos(o) = __pos__(o)                   -x +x x+y x-y x*y x/y 1 x//y 1 x%y 2 x**y 2
                                                                          div(a,b)   = __div__(a,b)        pow(a,b) = __pow__(a,b)               1
                                                                                                                                                   With from __future__ import division, / is true division (1/2→0.5),
       Arithmetic Overriding
                                                                          mod(a,b)   = __mod__(a,b)                                                and // is floor division (1//2→0). Else for integers / is still floor division.
__add__(self,other) → value: called for self + other                                                                                             2
                                                                                                                                                   % is remainder operator, ** is power elevation operator (same as pow).
                                                                                 Bit Level
__sub__(self,other) → value: called for self - other
__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)                                          Some functions in builtins.
__truediv__(self,other) → value: called2 for self / other                 inv(o) = invert(o) = __inv__(o) = __invert__(o)                        abs(x) → absolute value of x
__floordiv__(self,other) → value: called for self // other                       Sequences                                                       divmod(x,y) → (x/y,x%y)
__mod__(self,other) → value: called for self % other                                                                                             oct(integer) → str: octal representation of integer number
                                                                          concat(a,b) = __concat__(a,b)
__divmod__(self,other) → value: called for divmod(self,other)                                                                                    hex(integer) → str: hexadecimal representation of integer number
                                                                          contains(a,b) = __contains__(a,b)
__pow__(self,other) → value: called for self ** other                                                                                            Representation formating functions in strings Formating (p5) and
                                                                          countOf(a,b)
__nonzero__(self)→ value: called for nonzero(self)                                                                                                Localization (p6).
                                                                          indexOf(a,b)
__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)                                    Standard floating point functions/data in standard math module.
__abs__(self) → value: called for abs(self)                               getitem(a,b) = __getitem__(a,b)                                        acos(x) → float: radians angle for x cosinus value : [-1…1] →[0…π]
__iadd__(self,other) ➤ called for self += other                           delitem(a,b) = __delitem__(a,b)                                        asin(x) → float: radians angle for x sinus value : [-1…1] →[-π/2…+π/2]
__isub__(self,other) ➤ called for self -= other                           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…+π/2[
                                                                          getslice(a,b,c) = __getslice__(a,b,c)                                  atan2(x,y) → float: randians angle for x/y tangent value
__idiv__(self,other) ➤ called1 for self /= other                          delslice(a,b,c) = __delslice__(a,b,c)
__itruediv__(self,other) ➤ called2 for self /= other                                                                                             ceil(x) → float: smallest integral value >= x
__ifloordiv__(self, other) ➤ called for self //= other                           Type Testing                                                    cos(x) → float: cosinus value for radians angle x
__imod__(self,other) ➤ called for self %= other                            These functions must be considered as not reliable.                   cosh(x) → float: hyperbolic cosinus value for radians angle x
__ipow__(self,other) ➤ called for self **= other                          isMappingType(o)                                                       exp(x) → float: exponential of x = ex
 1
   without / 2 with from __futur__ import division                        isNumberType(o)                                                        fabs(x) → float: absolute value of x
 Binary operators __xxx__ have also __rxxx__ forms, called when target    isSequenceType(o)                                                      floor(x) → float: largest integral value = == != .                                                                                                          ldepx(x,i) → float: x multiplied by 2 raised to i power: x * 2i
Test objects identity with is and is not (compare on id(obj)).            BOOLEANS                                                               log(x) → float: neperian logarithm of x
Direct composition of comparators is allowed in expressions : x o2)     True : if not false. True → 1.                                         modf(x) → (float{2}): (f,i) f signed fractional part of x, i signed integer part of
       Comparison Overriding                                              bool(expr) → True | False                                               x
                                                                          Logical not : not expr                                                 pow(x,y) → float: x raised to y power (xy)
__lt__(self,   other)→ bool1: called for self < other
                                                                          Logical and : expr1 and expr2                                          sin(x) → float: sinus value for radians angle x
__le__(self,   other)→ bool1: called for self  other                     Logical or : expr1 or expr2                                            sinh(x) → float: hyperbolic sinus value for radians angle x
__ge__(self,   other)→ bool1: called for self >= other                     Logical and and or use short path evaluation.                         sqrt(x) → float: square root of x (√x)
__eq__(self,   other)→ bool1: called for self == other                           Bool Cast Overriding                                            tan(x) → float: tangent value for radians angle x
__ne__(self,   other)→ bool1: called for self != other                                                                                           tanh(x) → float: hyperbolic tangent value for radians angle x
                                                                          __nonzero__(self) → bool: test object itself1
                                   and for self  other                   1                                                                     pi → float: value of π (pi=3.1415926535897931)
                                                                             If __nonzero__ undefined, look at __len__, else object is true.
__cmp__(self,other)→ int: called for self compared to other,                                                                                     e → float: value of neperian logarithms base (e=2.7182818284590451)
 self0              NUMBERS                                                                 Module cmath provides similar functions for complex numbers.
 1
   Any value usable as boolean value, or a NotImplemented value if        Builtin integer types : int (like C long), long (unlimited integer)           Random Numbers
 cannot compare with such other type.                                     int(expr[,base=10]) → int: cast of expr                                Randomization functions in standard random module. Module functions

                                    4a                                                                           4b                                                                     4c
use an hidden, shared state, Random type generator (uniform              __irshift__(self,other) ➤ called for self >>= other                              Most string methods are also available as functions in the standard
 distribution).                                                                                                                                            string module.
Functions also available as methods of Random objects.                    STRINGS                                                                         s.capitalize() → string with first char capitalized1
seed([x]) ➤ initialize random number generator                            Simple quoted 'Hello' or double-quoted "Hello".                                 s.center(width[,fillchar]) → string centered
random()→ float: random value in [0.0, 1.0[                               Use triple [simple|double] quotes for multi-lines strings :                     s.count(sub[,start[,end]]) → int: count sub occurences
randint(a,b)→ int: random value in [a, b]                                      """Hello,                                                                  s.decode([encoding[,errors]]) → unicode: text decoded - see encodings
uniform(a, b)→ float: random value in [a, b[                                   how are you ?"""                                                            (p12)
getrandbits(k)→ long: with k random bits                                  Strings are immutable (once created a string cannot be modified in              s.encode([encoding[,errors]]) → str: text encoded - see encodings (p12)
randrange([start,]stop[,step])→ int: random value in range(start, stop,    place).                                                                        s.endswith(suffix[,start[,end]]) → bool: test text ending
 step)                                                                    Strings can contain binary data, including null chars (chars of code 0).        s.expandtabs([tabsize]) → string with tabs replaced by spaces
choice(seq)→ value: random item from seq sequence                         Strings are sequences, see Indexing (p8) for chars indexation (slicing)         s.find(sub[,start[,end]]) → int/-1: offset of sub
shuffle(x[,rndfct]) ➤ items of x randomly reordered using rndfct()         and other operations.                                                          s.index(sub[,start[,end]]) → int: offset of sub - may raise ValueError
sample(population,k)→ list: k random items from polulation                chr(code)→ str: string of one char                                              s.isalnum() → bool: non empty string with all alphanumeric chars1
Alternate random distributions : betavariate(alpha,beta),                 ord(char)→ int: code                                                            s.isalpha() → bool: non empty string with all alphabetic chars1
 expovariate(lambd), gammavariate(alpha,beta), gauss(mu,sigma),           str(expr)→ str: readable textual representation of expr - if available          s.isdigit() → bool: non empty string with all digit chars1
 lognormvariate(mu, sigma), normalvariate(mu,sigma),                      `expr` → str: readable textual representation of expr - if available            s.islower() → bool: non empty string with all lower chars1
 vonmisesvariate(mu,kappa), paretovariate(alpha),                         repr(expr)→ str: evaluable textual representation of expr - if available        s.isspace() → bool: non empty string with all space chars1
 weibullvariate(alpha,beta).                                                       Escape sequences                                                       s.istitle() → bool: non empty string with titlecase words1
Alternate random generator WichmannHill class.                            \a   -   bell               \v - vertical tab                                   s.isupper() → bool: non empty string with all upper chars1
Direct generator manipulation : getstate(), setstate(state),              \b   -   backspace          \' - single quote                                   s.join(seq) → string: seq[0]+s+seq[1]+s+…+seq[n-1]
 jumpahead(n).                                                            \e   -   escape             \" - double quote                                   s.ljust(width[,fillchar]) → text string left aligned2
In module os, see :                                                       \f   -   form feed          \\ - backslash                                      s.lower() → text string lowered1
os.urandom(n) → str: n random bytes suitable for cryptographic use        \n   -   new line           \ooo - char by octal ooo value                      s.lstrip([chars]) → string text with leading chars2 removed
       Other Math Modules                                                 \r   -   carriage return    \xhh - char by hexadecimal hh value                 s.replace(old,new[,count]) → string with count firsts old replaced by new
                                                                          \t   -   horizontal tab     \ - continue string on next line.          s.rfind(sub[,start[,end]]) → int/-1: last offset of sub
Advanced matrix, algorithms and number crunching in third party                                                                                           s.rindex(sub[,start[end]])→ int: last offset of sub - may raise ValueError
 modules like numpy (evolution of numarray / Numeric), gmpy               And for Unicode strings :
                                                                          \uxxxx - unicode char by 16 bits hexadecimal xxxx value.                        s.rjust(width[,fillchar]) → string text right aligned2
 (multiprecision arithmetic), DecInt, scipy, pyarray, …                                                                                                   s.rsplit([sep[,maxsplit]])→ [string]: rightmost words delim. by sep2
                                                                          \Uxxxxxxxx - unicode char by 32 bits hexadecimal xxxxxxxx value.
See sites SciPy, BioPython, PyScience,…                                                                                                                   s.rstrip([chars]) → string with trailing chars2 removed
                                                                          \N{name} - unicode char by name in the Unicode database.
       Numbers Casts Overriding                                            Keep \ escape chars by prefixing string literals with a r (or R) - for 'raw'   s.split([sep[,maxsplit]]) → [string]: words delimited by sep2
                                                                           strings (note : cannot terminate a raw string with a \).                       s.splitlines([keepends]) → [string]: list of text lines
__int__(self) → int: called for int(self)
                                                                                                                                                          s.startswith(suffix[,start[,end]]) → bool: test text begining
__long__(self) → long: called for long(self)                                  Unicode strings                                                             s.strip([chars]) → string text with leading+trailing chars2 removed
__float__(self) → float: called for float(self)                           Quoted as for str, but with a u (or U) prefix before the string : u"Voiçi"      s.swapcase() → string with case switched1
__complex__(self) → complex: called for complex(self)                        U"""Une bonne journée                                                        s.title() → string with words capitalized1
__oct__(self) → str: called for oct(self)                                    en perspective."""                                                           s.translate(table[,deletechars]) → string: cleaned, converted3
__hex__(self) → str: called for hex(self)                                  Can mix strings prefixs r (or R) and u (or U).                                 s.upper() → string uppered1
__coerce__(self,other) → value: called for coerce(self,other)             You must define your source file encoding so that Python knows how to           s.zfill(witdh) → string: string prefixed with zeroes to match width
                                                                           convert your source literal strings into internal unicode strings.
BIT LEVEL OPERATIONS                                                      unichr(code) → unicode: string of one char
                                                                                                                                                           1
                                                                                                                                                           2
                                                                                                                                                             Locale dependant for 8 bits strings.
                                                                                                                                                             Default chars/separator/fillchar is space.
Work with int and long data.                                              ord(unicode char) → int: unicode code                                            3
                                                                                                                                                             For str table must be a string of 256 chars - see string.maketrans().
    Operators                                                             unicode(object[,encoding[,errors]]) → unicode: unicode                           For Unicode no deletechars, and table must be a map of unicode
~x → inverted bits of x                                                   sys.maxunicode → int: maximum unicode code=fct(compile time option)              ordinals to unicode ordinals.
x^y → bitwise exclusive or on x and y                                                Unicode Chars Informations                                                Formating
x&y → bitwise and on x and y                                              Module unicodedata contains informations about Unicode chars                    Use % operator between format string and arguments : string%args
x|y → bitwise or on x and y                                                properties, names.                                                             Formating string contains %[(name)][flag][width][.precision]code
xn → x shifted right by n bits (zeroes inserted)                        name(unichr[,default]) → str: unicode name - may raise ValueError               If use %(name)… → args = mapping with name as keys.
Binary structures manipulations in standard module struct.                decimal(unichr[,default]) → int: decimal value - may raise ValueError             For mapping, args can be an object with __getitem__ method - see
Advanced binary structures mapping and manipulation in third party        digit(unichr[,default]) → int: digit value - may raise ValueError                 Overriding Mapping Operations (p8).
 modules : ctypes, xstruct, pyconstruct, …                                numeric(unichr[,default]) → float: numeric value - may raise ValueError
                                                                                                                                                                  Format char codes
                                                                          category(unichr) → str: general unicode category of char
       Bit Level Overriding                                                                                                                               d   signed int. decimal : -324             i   signed int. decimal : -324
                                                                          bidirectional(unichr) → str: bidir category of char, may be empty string
__and__(self,other) → value: for self & other                             combining(unichr) → str/0: canonical combining class of char as integer         o   unsigned octal : 774                   u   unsigned decimal 6953
__or__(self,other) → value: for self | other                              east_asian_width(unichr) → str: east asian width                                x   unsigned hexa : f3a                    X   unsigned hexa : F3A
__xor__(self,other) → value: for self ^ other                             mirrored(unichr) → int: mirrored property in bidi text, 1 if mirrored else 0    e   float. point exp. : -3.256e-12         E   float. point exp. : -3.256E-12
__lshift__(self,other) → value: for self > other                         normalize(form, unistr) → str: normal form of string - form in 'NFC',           g   like e or f                            G   like E or F
__invert__(self) → value: for ~self                                        'NFKC', 'NFD', 'NFKD'                                                          c   character (1 char str or code)         %   %% → %
__iand__(self,other) ➤ called for self &= other                           unidata_version → str: version of Unicode database used                         r   object format like repr(object)        s   object format like str(object)
__ior__(self,other) ➤ called for self |= other                                                                                                                    Templates
__ixor__(self,other) ➤ called for self ^= other                              Methods and Functions
__ilshift__(self,other) ➤ called for self
tmpl = string.Template(template_string)                                         expr+ ➤ match 1 or more repetitions of expr (as much as possible)                        Matching and Searching
tmpl.substitute(mapping[,**kwargs]) → string: template filled                   expr? ➤ match 0 or 1 expr                                                         Can use re functions, or compile expressions into SRE_Pattern objects
tmpl.safe_substitute(mapping[,**kwargs]) → string: template filled              expr*? ➤ match like expr* but as few as possible                                   and use their methods.
tmpl.template → string                                                          expr+? ➤ match like expr+ but as few as possible                                  See Flag Options supra for flags parameters.
 Can subclass Template to build your own templating (see doc, sources).         expr?? ➤ match like expr? but as few as possible                                  search(pattern,string[,flags])→ MatchObject/None: scan throught string to
See also modules formatter.                                                     expr{m} ➤ match m repetitions of expr                                              find substrings matching pattern
       Wrapping                                                                 expr{[m],[n]} ➤ match from m to n repetitions of expr, missing m default to 0     match(pattern,string[,flags])→ MatchObject/None: try to match string with
                                                                                  and missing n default to infinite                                                pattern
Module textwrap has a TextWrapper class and tool functions.                     expr{[m],[n]}? ➤ match like expr{[m],[n]} but as few as possible                  split(pattern,string[,maxsplit=0])→ [string]: split string by occurences of
tw = textwrap.TextWrapper([…]) → new text wrapper using named params            [set] ➤ match one char in the set defined by :                                     pattern - if maxsplit specified, remainder is put in last item of list
 as corresponding attributes values                                                   ^ → at begining, invert set definition                                      findall(pattern,string[,flags])→ [string]/[(string)]: find non-overlapping
tw.width → int: max length of wrapped lines (default 70)
                                                                                      x-y → chars from x to y                                                      substrings matching pattern - eventually empty matchs - return list of tuples if
tw.expand_tabs → bool: replace tabs by text.expandtabs() (default True)
                                                                                      \x → see Escape sequences for strings (p5)                                   pattern has groups
tw.replace_whitespace → bool: replace each whitespace by space (default
                                                                                      \- , \] → chars - and ] (- and ] at the beginning match - and ] chars)      finditer(pattern,string[,flags])→ iterator over [MatchObject] - same as
 True)
                                                                                      x → char x (including other re metacharacters)                               findall but with an iterator
tw.initial_indent → string: prepend to first wrapped line (default '')
                                                                                exprA|exprB ➤ match exprA or exprB, short path evaluation                         sub(pattern,repl,string[,count=0])→ string: replace substrings matching
tw.subsequent_indent → string: prepend to other wrapped lines (default '')
                                                                                (expr) ➤ match expr and build a numbered group                                     pattern by repl - repl as string can contain back references1 to identified
tw.fix_sentence_endings → bool: try to separate sentences by two spaces                                                                                            substring - repl as fct(MatchObject) return replacement string - pattern may
                                                                                (?[i][L][m][s][u][x]) ➤ (at least one ot iLmsux char) group match empty
 (default False)                                                                                                                                                   be RE_Pattern object
                                                                                   string, modify options flags for entire expression - see I L M S U X options
tw.break_long_words → bool: break words longer than width (default True)                                                                                          subn(pattern,repl,string[,count=0])→ (string,int): same as sub, 2nd item is
                                                                                (?:expr) ➤ match expr but dont build a group
tw.initial_indent → string: prepend to first wrapped line (default '')                                                                                             count of substitutions
                                                                                (?Pexpr) ➤ match expr and build a group numbered and named (name
tw.wrap(text) → [string]: list of text lines, each with max width length - no                                                                                     escape(string)→ string: non-alphanumerics backslashed
                                                                                   must be valid Python identifier)
 final newline                                                                  (?P=name) ➤ match text matched by earlier group named name
tw.fill(text) → string: whole text, lines wrapped using newlines                                                                                                  If you need to reuse a pattern, compile it one time for all.
                                                                                (?#text) ➤ no match, text is just a comment                                       pat = re.compile(pattern[,flags])→ RE_Pattern object
Two convenient functions use temporary TextWrapper, built using
                                                                                (?=expr) ➤ match if match expr but don't consume input                            pat.match(string[,pos[,endpos]]) → same as match function2
 named parameters corresponding to attributes.
                                                                                (?!expr) ➤ match if doesn't match expr but don't consume input                    pat.search(string[,pos[,endpos]]) → same as search function2
wrap(text[,width=70[,…]]) → [string]
                                                                                (?.
       Expressions                                                               and $ match only beginning and end of string.                                     1
                                                                                                                                                                    Using part of string between pos and endpos.
Metacharacters : . ^ $ * + ? { } [ ] \ | ( ), may use \ escape.                 DOTALL (S) : make . match any char including newline. Else newline                 Group number 0 correspond to entire matching.
. ➤ match any character except a newline (including newline with DOTALL          excluded.
                                                                                                                                                                       Localization
                                                                                UNICODE (U) : make \w \W \b \B unicode dependant.
  option)                                                                                                                                                         Standard module locale provide posix locale service (internationa-
^ ➤ match start of string (and start of lines with MULTILINE option)            VERBOSE (X) : ignore whitespaces and make # starting comments (except
                                                                                 when space and # are escaped or in char class).                                   lization).
$ ➤ match end of string (and end of lines with MULTILINE option)                                                                                                  setlocale(category[,locale]) → current/new settings: if locale specified (as
expr* ➤ match 0 or more repetitions of expr (as much as possible)                                                                                                  string or as tuple(language code, encoding)) then modify locale settings for

                                     6a                                                                                 6b                                                                              6c
category and return new one - if locale not specified or None, return current           key                          nl_langinfo() value usage                     lngettext(singular,plural,n)→ string: like ngettext(), using preferred
 locale - not thread safe                                                        ERA_D_FMT            usable as format for strftime() for date with era              encoding
localeconv()→ dict: database of local conventions                                ALT_DIGITS           up to 100 values representing 0 to 99                         dngettext(domain,singular,plural,n)→ string: like ngettext(), looking in
nl_langinfo(option)→ string: locale-specific informations - not available on                                                                                         specified domain.
 all systems - options may vary on systems - see options p7                             localeconv keys                                                             ldngettext(domain,singular,plural,n)→ string: like dngettext(), using
getdefaultlocale([envvars])→(language code, encoding): try to determine                     key                                   meaning                            preferred encoding
 default locale settings                                                         currency_symbol           Local currency symbol for monetary values.                Generally _ is bound to gettext.gettext, and translatable strings are
getlocale([category])→ current LC_* setting for category - category default      decimal_point             Decimal point character for numbers.                      written in sources using _('thestring'). See docs for usage
 to LC_CTYPE - for language code and ancoding it may be None                     frac_digits               Number of fractional digits used in local                 examples.
getpreferredencoding([do_setlocale])→ str: user preffered encoding for                                      formatting of monetary values.                                 Class based API
 text data - set do_setlocale to False to avoid possible call to setlocale()     grouping                  [int]: relative positions of 'thousands_sep' in
                                                                                                            numbers. CHAR_MAX at the end stop grouping.             The recommended way. Module gettext defines a class Translations,
normalize(localename)→ normalized locale code for localename - usable with
                                                                                                            0 at the end repeat last group.                          dealing with .mo translation files and supporting str/unicode strings.
 setlocale() - return localename if normalization fails
                                                                                                                                                                    find(domain[,localedir[,languages[,all]]])→ str/None: .mo file name for
resetlocale([category]) ➤ reset locale for category to default setting -         int_curr_symbol           International currency symbol of monetary
                                                                                                                                                                     translations (search in localedir/language/LC_MESSAGES/domain.mo)
 category default to LC_ALL                                                                                 values.
                                                                                                                                                                    translation(domain[,localedir[,languages[,class_[,fallback[,codeset]]]]])
strcoll(s1,s2)→ int: compare two strings - follow LC_COLLATE setting -           int_frac_digits           Number of fractional digits used in international
                                                                                                                                                                     →Translations: object from class class_ (default to GNUTranslations,
 return 0 if s1==s2, s2                                                               formatting of monetary values.
                                                                                                                                                                     constructor take file object as parameter) - if true fallback allow to return a
strxfrm(string)→ string:transform string for locale-aware comparison             mon_decimal_point         Decimal point used for monetary values.
                                                                                                                                                                     NullTranslations if no .mo file is found, default to false (raise IOError) -
format(format,val[,grouping])→ string:convert val float using format (%          mon_grouping              Equivalent to 'grouping', used for monetary
                                                                                                                                                                     codeset change charset used to encode translated strings
 operator conventions) - follow LC_NUMERIC settings (decimal point, + grouping                              values.
                                                                                                                                                                    install(domain[,localedir[,unicode[,codeset]]]) ➤ install _ function in
 if it is true)                                                                  mon_thousands_sep         Group separator used for monetary values.
                                                                                                                                                                     Python's builtin namespace, to use _('thestring')
str(float)→ string: convert float - follow LC_NUMERIC settings (decimal point)   n_cs_precedes             True if currency symbol preceed negative
atof(string)→ float: convert string to float - follow LC_NUMERIC settings                                  monetary values, false if it follow.                            Null Translations
atoi(string)→ int: convert string to integer - follow LC_NUMERIC settings        n_sep_by_space            True if there is a space between currency                The NullTranslations is a base class for all Translations.
CHAR_MAX → symbolic constant used by localeconv()                                                          symbol and negative monetary value.                      t.__init__([fp]) ➤ initialize translations: fp is a file object - call _parse(fp) if
       Categories                                                                n_sign_posn               Position of negative sign for monetary values1.           it is not None
                                                                                 negative_sign             Symbol used to annotate a negative monetary              t._parse(fp) ➤ nothing: subclasses override to read data from the file
LC_CTYPE → character type - case change behaviour                                                           value.                                                  t.add_fallback(fallback) ➤ add fallback used if cannot found translation for
LC_COLLATE → strings sorting - strcoll() and strxfrm() functions                 p_cs_precedes             True if currency symbol preceed positive                  a message
LC_TIME → time formating - time.strftime()                                                                 monetary values, false if it follow.                     Define methods gettext, lgettext, ngettext, lngettext as in the base
LC_MONETARY → monetary values formating - options from localeconv()              p_sep_by_space            True if there is a space between currency                 API. And define speciale methods ugettext and ungettext returning
LC_MESSAGES → messages display - os.strerror() - not for Python messages                                   symbol and positive monetary value.                       unicode strings (other forms return encoded str strings). Return
LC_NUMERIC → numbers formatting - format(), atoi(), atof() and str() of          p_sign_posn               Position of positive sign for monetary values1.           translated message, forwarding to fallback if it is defined. Overriden in
 this module (dont modify normal Python number formating)                        positive_sign             Symbol used to annotate a positive monetary               subclasses.
LC_ALL → all locales - used to change/retrieve the locale for all categories                                value.                                                  t.info()→ return protected _info attribute
       nl_langinfo options                                                       thousands_sep             Character used between groups of digits in               t.charset()→ return protected _charset attribute
        key                         nl_langinfo() value usage                                              numbers.                                                 t.output_charset()→ return protected _output_charset attribute
CODESET             name of character encoding                                    1
                                                                                    Possible values : 0=currency and value surrounded by parentheses,                (defining encoding used to return translated messages)
D_T_FMT             usable as format for strftime() for time and date             1=sign should precede value and currency symbol, 2=sign should                    t.set_output_charset(charset) ➤ set _output_charset attribute
D_FMT               usable as format for strftime() for date                      follow value and currency symbol, 3=sign should immediately precede               t.install([unicode]) ➤ bind _ in builtin namespace to self.gettext() or
T_FMT                                                                             value, 4=sign should immediately follow value, LC_MAX=nothing                      self.ugettext() upon unicode (default to false)
                    usable as format for strftime() for time
T_FMT_AMPM          usable as format for strftime() for time in am/pm             specified in this locale.                                                                GNU Translations
                    format                                                            Multilingual Support                                                          The GNUTranslations class (subclass of NullTranslations) is based on
DAY_1…DAY_7         name of the nth day of the week - first day is sunday        Standard module gettext for internationalization (I18N) and localization            GNU gettext and .mo files.
ABDAY_1…            abbreviated name of the nth day of the week - first           (L10N) services - based on GNU gettext API + higher interface. See docs           Messages ids and texts are coerced to unicode.
 ABDAY_7            day is sunday                                                 for explanations about tools usage.                                               Protected _info attribute contains message translations.
MON_1… MON_12       name of the nth month                                                                                                                           Translation for empty string return meta-data (see doc).
                                                                                        Base API
                                                                                                                                                                    Define methods gettext, lgettext, ugettext, ngettext, lngettext,
ABMON_1…            abbreviated name of the nth month                            bindtextdomain(domain[,localedir])→ str: bounded directory - bind domain            ungettext as in NullTranslations interface - same rules for return
 ABMON_12                                                                         to localedir directory if specified (used when searching for .mo files)            values (str/unicode). Message translations are searched in catalog,
RADIXCHAR           radix character (decimal dot/comma/…)                        bind_textdomain_codeset(domain[,codeset])→ codeset binding: bind                    then in fallback if defined, and if no translation is found, message itself
THOUSEP             separator character for thousands                             domain to codeset if specified - change xxgettext() returned strings encoding      is returned (for n… methods, return singular forms if n=1 else plural
YESEXPR             regular expression (of C library!) usable for yes reply      textdomain([domain])→ global domain: set global domain if specified and not         forms).
NOEXPR                                                                            None
                    regular expression (of C library!) usable for no reply
                                                                                 gettext(message)→ string: localized translation of message - based on              CONTAINERS
CRNCYSTR            currency symbol, preceded by - if should appear               current global domain, language, and locale directory - usually aliased as _ in
                    before the value, by + if should appear after the                                                                                               Basic containers kind :
                                                                                  local namespace                                                                   -sequences (ordered collections) : list, tuple,str, any iterable,…
                    value, by . if should replace radix character                lgettext(message)→ string: like gettext(), using preferred encoding
ERA                                                                                                                                                                 -mappings (unordered key/value) : dict…
                    era - generally not defined - same as E format in            dgettext(domain,message)→ string: like gettext(), looking in specified
                    strftime()                                                                                                                                      -sets (unordered collections) : set, frozenset…
                                                                                  domain.
ERA_YEAR            year in era                                                  ldgettext(domain,message)→ string: like dgettext(), using preferred                    Operations on Containers
ERA_D_T_FMT         usable as format for strftime() for date and time             encoding                                                                          For strings, items are chars. For mappings, items are keys.
                     with era                                                    ngettext(singular,plural,n)→ string: like gettext(), but consider plural           item in container → bool: test item ∈ container1
                                                                                  forms (see Python and GNU gettext docs)                                           item not in container → bool: test item ∉ container1
                                     7a                                                                                      7b                                                                            7c
You can also read
Next part ... Cancel