You are on page 1of 2

20102012 - Laurent Pointal Abrg v1.3.

0 - English Summary necessarily incomplete to keep on one paper sheet, see


Licence Creative Commons Attribution 2
Python 3.2 Reference Card http://docs.python.org/py3k.

Cheat Sheet Symbols Bits Manipulations IndexError - KeyError - AttributeError


optional instructions , repeatable instructions, (with integers) a<<b a>>b a&b a|b a^b - IOError - ImportError - NameError -
immutable data, ordered container ( non String SyntaxError - TypeError -
ordered), constant, variable, type, function & Escape : \ NotImplementedError
.method, parameter, [,optional parameter], Managed Context
\\ \ \' ' \" "
keyword, literal, module, file. with managed() as v :
\n new line \t tab # Block executed in a managed context
Introspection & Help
\N{name} unicode name Function Definition and Call
help([objet or "subject"])
\xhh hh hexa \0oo oo octal
id(objet) dir([object]) vars([object]) def fname(x,y=4,*args,**kwargs):
\uhhhh et \Uhhhhhhhh unicode hexa hhhh # function block or, if no code, pass
locals() globals() prefix r, disable \ : r"\n" \n
Qualified Access return ret_expression
Formating : "{model}".format(data) x: simple parameter
Separator . between a namespace and a name in "{} {}".format(3,2)
that space. Namespaces : object, class, function, "{1} {0} {0}".format(3,9) y: parameter with default value
"{x} {y}".format(y=2,x=5) args: variable parameters by order (tuple)
module, package. Examples : "{0!r} {0!s}".format("text\n")
math.sin(math.pi) f.__doc__ "{0:b}{0:o}{0}{0:x}".format(100) kwargs: named variable parameters (dict)
MyClasse.nbObjects() "{0:0.2f}{0:0.3g}{0:.1e}".format(1.45) ret_expression: tuple return multiple values
point.x rectangle.width() Operations Call
Base Types s*n (repeat) s1+s2 (concatenate) *= += res = fname(expr,param=expr,*tuple,**dict)
undefined : None .split([sep[,n]]) .join(iterable) Anonymous Functions
.splitlines([keepend]) .partition(sep)
Boolean : bool True / False lambda x,y: expression
.replace(old,new[,n]) .find(s[, start[,end]])
bool(x) False if x nul or empty Sequences & Indexation
.count(s[, start[,end]]) .index(s[, start[,end]])
Integer : int 0 165 -57 .isdigit() & Co .lower() .upper() for any direct access ordered container.
binary:0b101 octal:0o700 hexa:0xf3e .strip([chars]) ith Item : x[i]
int(x[,base]) .bit_length() .startswith(s[,start[,end]]) Slice : x[start:end] x[start:end:step]
Floating : float 0.0 -13.2e-4 .endsswith(s[,start[,end]]) i, start, end, step integers positive or negative
float(x) .as_integer_ratio() .encode([enc[, err]]) start/end missing up to start/end
Complex : complex 0j -1.2e4+9.4j ord(c) chr(i)
-6 -5 -4 -3 -2 -1
complex(re[,img]) .real .imag Conditional Expression x[i]
.conjugate() 0 1 2 3 4 5
String : str '' 'toto' "toto" Evaluated as a value.
"""multiline toto""" expr1 if condition else expr2 x
str(x) repr(x) Flow Control 0 1 2 3 4 5 6
Identifiers, Variables & Assignment x[st:end]
statements blocs delimited by indentation (idem -6 -5 -4 -3 -2 -1
Identifiers : [a-zA-Z_] followed by or one or functions, classes, methods). Convention 4 Modification (if sequence is modifiable)
multiple [a-zA-Z0-9_], accent and non-latin spaces - tune editor. x[i]=expressionx[start:end]=iterable
alphabetical chars allowed (but should be Alternative If del x[i] del x[start:end]
avoided). if condition1: Containers & Iterables
name = expression # block executed if condition1 is true
name1,name2,nameN = sequence An iterable provide values one after the other. Ex :
elif condition2: containers, dictionary views, iterable objets,
sequence containing N items # block executed if condition2 is true generator functions
name1 = name2 = nameX = expression else: Generators (calculate values when needed)
unpacking sequence: first,*remain=sequence # block executed if all conditions are false range([start,]end[,step])
increment : name=name+expression Loop Over Sequence ( expr for var in iter if cond )
augmented assignment : name+=expression for var in iterable: Generic Operations
(with other operators too) # block executed with var being successively v in containeur v not in containeur
deletion : del nom # each of the values in iterable len(containeur) enumerate(iter[,start])
Identifiers Conventions else: iter(o[,sent]) all(iter) any(iter)
Details in PEP 8 Style Guide for Python # executed after, except if exit for loop by break filter(fct,iter) map(fct,iter,)
A_CONSTANT uppercase var with multiple variables : for x,y,z in max(iter) min(iter) sum(iter[,start])
alocalvar lowercase without _ var index,valuer : for i,v in enumerate() reversed(seq) sorted(iter[,k][,rev])
a_global_var lowercase with _ iterable : see Containers & Iterables On sequences : .count(x) .index(x[,i[,j]])
a_function lowercase with _ Loop While String : (sequence of chars)
a_method lowercase with _ while condition: cf. types bytes, bytearray, memoryview to
AClass title directly manipulate bytes (+notation
# block executed while condition is true
AnExceptionError title with Error at end b"bytes").
else:
amodule lowercase rather without _
# executed after, except if exit while loop by List : list [] [1,'toto',3.14]
apackage lowercase rather without _ break list(iterable) .append(x)
Avoid l O I (l min, o maj, i maj) alone. Loop Break : break .extend(iterable) .insert(i,x) .pop([i])
_xxx internal usage Immediate exit of the loop, without going through else .remove(x) .reverse() .sort()
__xxx modified _Class__xxx block. [ expr for var in iter if cond ]
__xxx__ spcial reserved name Loop Jump : continue Tuple : tuple () (9,'x',36) (1,)
Logical Operations Immediate jump at loop start with next iteration. tuple(iterable) 9,'x',36 1,
a<b a<=b a>=b a>b a=ba==b aba!=b Errors Processing: Exceptions Set : set {1,'toto',42}
not a a and b a or b (expr) try: set(iterable) frozenset(iterable)
combined : 12<x<=34 # block executed in normal case .add(x) .remove(x) .discard(x)
Maths except exc as e: .copy() .clear() .pop()
# block executed if an error of type exc is |, &, diff-, sym.diff^, <
-a a+b a-b a*b a/b aba**b (expr) detected |= &= -= ^=
euclidian division a=b.q+r q=a//b et r=a%b else: Dictionnary (associative array, map) : dict
et q,r=divmod(a,b) # block executed in case of normal exit from try {} {1:'one',2:'two'}
|x|abs(x) xy%zpow(x,y[,z]) round(x[,n]) finally: dict(iterable) dict(a=2,b=4)
following functions/data in module math # block executed in all case dict.fromkeys(seq[,val])
e pi ceil(x) floor(x) trunc(x) exc for n types : except (exc1,exc2,excn) d[k]=expr d[k] del d[k]
exexp(x) log(x) sqrt(x) as e optional, fetch exception .update(iter) .keys() .values()
detect specific exceptions (ex. ValueError) and .items() .pop(k[,def]) .popitem()
cos(x) sin(x) tan(x) acos(x) asin(x)
not generic ones (ex. Exception). .get(k[,def]) .setdefault(k[,def])
atan(x) atan2(x,y) hypot(x,y) .clear() .copy()
cosh(x) sinh(x) Raising Exeptions (error situation)
items, keys, values iterable views.
following functions in module random raise exc([args])
Input/Output & Files
raise propagate exception
seed([x]) random() randint(a,b) print("x=", x[,y ][,sep=][,end=][,file=])
randrange([start],end[,step]) uniform(a,b) Some exception classes : Exception -
ArithmeticError - ZeroDivisionError - input("Age ? ") str
choice(seq) shuffle(x[,rnd]) sample(pop,k)
explicit cast to int or float if needed. def __format__(self,format_spec): def __getattr__(self,name):
File : f=open(name[,mode][,encoding=]) # return a string following specified format # called if name not found as existing attribute
mode : 'r' read (default) 'w' write 'a' append Special Comparison Mehods def __getattribute__(self,name):
'+' read write 'b' binary mode Return True, False or NotImplemented. # called in all case of name access.
encoding : 'utf-8' 'latin1' 'ascii' x<y def __lt__(self,y): def __setattr__(self,name,valeur):
.write(s) .read([n]) .readline() x<=y def __le__(self,y): def __delattr__(self,name):
.flush() .close() .readlines() def __dir__(self): # return a list
x==y def __eq__(self,y):
Loop in lines :for line in f :
x!=y def __ne__(self,y): Accessors
Managed context (close) : with open() as f:
x>y def __gt__(self,y): Property
in module os (see also os.path):
x>=y def __ge__(self,y): class C(object):
getcwd() chdir(path) listdir(path) def getx(self):
Special Operations Methods
Command line parameters in sys.argv def setx(self,value):
Modules & Packages
Return a new object of the class, containing the
operation result, or NotImplemented if cannot def delx(self):
Module : script file extension .py (and C compiled
work with given y argument. x = property(getx,setx,delx,"docx")
modules). File toto.py module toto. x self # Simpler, accessor to y, with decorators
Package : directory with file __init__.py. Contains
x+y def __add__(self,y): @property
module files. def y(self): # read
x-y def __sub__(self,y):
Searched in the PYTHONPATH, see sys.path list. """docy"""
x*y def __mul__(self,y): @y.setter
Module Sample :
#!/usr/bin/python3 x/y def __truediv__(self,y): def y(self,valeur): # modification
# -*- coding: utf-8 -*- x//y def __floordiv__(self,y): @y.deleter
"""Module documentation - cf PEP257""" x%y def __mod__(self,y): def y(self): # deletion
# File: mymodule.py Descriptors Protocol
# Author: Joe Student divmod(x,y) def __divmod__(self,y):
# Import other modules, functions x**y def __pow__(self,y): o.x def __get__(self,o,classe_de_o):
import math pow(x,y,z) def __pow__(self,y,z): o.x=v def __set__(self,o,v):
from random import seed,uniform del o.x def __delete__(self,o):
# Definition of constants and globals x<<y def __lshift__(self,y):
MAXIMUM = 4 x>>y def __rshift__(self,y): Special Function Call Method
lstFiles = [] x&y def __and__(self,y): Use an object as if it was a function (callable) :
# Definition of functions and classes
def f(x): x|y def __or__(self,y): o(params) def __call__(self[,params]):
"""Function documentation""" x^y def __xor__(self,y): Hash Special Method
-x def __neg__(self):
class Converter(object): For efficient storage in dict and set.
"""Class documentation""" +x def __pos__(self): hash(o) def __hash__(self):
nb_conv = 0 # class var abs(x) def __abs__(self): Define to None if object not hashable.
def __init__(self,a,b): ~x def __invert__(self):
"""init documentation""" Special Container Methods
self.v_a = a # instance var Following methods called after, on y if x don't o self
support required operation.
len(o) def __len__(self):
def action(self,y): y self
"""Method documentation""" o[key] def __getitem__(self,key):
x+y def __radd__(self,x):
o[key]=v def __setitem__(self,key,v):
# Module auto-test x-y def __rsub__(self,x):
del o[key] def __delitem__(self,key):
if __name__ == '__main__': x*y def __rmul__(self,x):
if f(2) != 4: # problem for i in o: def __iter__(self):
x/y def __rtruediv__(self,x): # return a new iterator on the container
Modules / Names Imports x//y def __rfloordiv__(self,x): reversed(o) def __reversed__(self):
import mymondule x%y def __rmod__(self,x): x in o def __contains__(self,x):
from mymodule import f,MAXIMUM divmod(x,y) def __rdivmod__(self,x): For notation [start:end:step], a slice object is given
from mymodule import * x**y def __rpow__(self,x): to container methods as value for key parameter.
from mymodule import f as fct x<<y def __rlshift__(self,x):
To limit * effect, define in mymodule : Slice: slice(start,end,step)
x>>y def __rrshift__(self,x): .start .stop .step .indices(lentgh)
__all__ = [ "f", "MAXIMUM"]
x&y def __rand__(self,x): Special Iterator Methods
Import via package :
from os.path import dirname x|y def __ror__(self,x): def __iter__(self):# return self
Class Definition x^y def __rxor__(self,x) : def __next__(self):# return next item
Special Augmented Assignment Methods If no more item, raise exception StopIteration.
Special methods, reserved names __xxxx__.
class ClassName([superclass]): Modify self object on which they are applied. Special Managed Context Methods
# class block x self Used for with statement.
class_variable = expression x+=y def __iadd__(self,y): def __enter__(self):
def __init__(self[,params]): x-=y def __isub__(self,y): # called at entry in the managed context
# initialization block x*=y def __imul__(self,y): # return value used for context' as variable
self.instance_variable = expression x/=y def __itruediv__(self,y): def __exit__(self,etype,eval,tb):
def __del__(self): x//=y def __ifloordiv__(self,y): # called at exit of managed context
# destruction block x%=y def __imod__(self,y): Special Metaclass Methods
@staticmethod # @decorator x**=y def __ipow__(self,y): __prepare__ = callable
def fct([,params]): x<<=y def __ilshift__(self,y): def __new__(cls[,params]):
# static method (callable without object) x>>=y def __irshift__(self,y): # allocation and return a new cls object
Membership Tests x&=y def __iand__(self,y): isinstance(o,cls)
isinstance(obj,class) x|=y def __ior__(self,y): def __instancecheck__(cls,o):
isssubclass(subclass,parentclass) x^=y def __ixor__(self,y): isssubclass(subclass,cls)
Objects Creation Special Numerical Conversion Methods def __subclasscheck__(cls,subclass):
Use the class as a function, parameters are passed Return the converted value. Generators
to constructor __init__. x self Calculate values when needed (ex.: range).
obj = ClasseName(params) complex(x) def __complex__(self): Generator functions, contains a statement yield.
Special Conversion Methods int(x) def __int__(self): yield expression
def __str__(self): yield from squence
float(x) def __float__(self): variable = (yield expression) transmission of
# return display string round(x,n) def __round__(self,n): values to the generator.
def __repr__(self): def __index__(self):
# return representation string If no more item, raise exception StopIteration.
# return an int usable as index Generator Function Control
def __bytes__(self): Special Attribute Access Methods
# return bytes string object generator.__next__()
def __bool__(self):
Access with obj.name. Exception generator.send(value)
AttributeError if attribute not found. generator.throw(type[,value[,traceback]])
# return a boolean
obj self generator.close()

You might also like