Even though this is a trivial example, the advantages of Python stand out.
Yorktown’s Computer Science I course has no prerequisites, so many of the
students seeing this example are looking at their first program. Some of them
are undoubtedly a little nervous, having heard that computer programming is
difficult to learn. The C++ version has always forced me to choose between
two unsatisfying options: either to explain the #include, void main(), {, and
} statements and risk confusing or intimidating some of the students right at
the start, or to tell them, “Just don’t worry about all of that stuff now; we will
talk about it later,” and risk the same thing. The educational objectives at
this point in the course are to introduce students to the idea of a programming
statement and to get them to write their first program, thereby introducing
them to the programming environment. The Python program has exactly what
is needed to do these things, and nothing more.
Comparing the explanatory text of the program in each version of the book
further illustrates what this means to the beginning student. There are thirteen
paragraphs of explanation of “Hello, world!” in the C++ version; in the Python
version, there are only two. More importantly, the missing eleven paragraphs
do not deal with the “big ideas” in computer programming but with the minutia
of C++ syntax. I found this same thing happening throughout the book.
Whole paragraphs simply disappear from the Python version of the text because
Python’s much clearer syntax renders them unnecessary.
Using a very high-level language like Python allows a teacher to postpone talking
about low-level details of the machine until students have the background that
they need to better make sense of the details. It thus creates the ability to put
“first things first” pedagogically. One of the best examples of this is the way in
which Python handles variables. In C++ a variable is a name for a place that
holds a thing. Variables have to be declared with types at least in part because
the size of the place to which they refer needs to be predetermined. Thus, the
idea of a variable is bound up with the hardware of the machine. The powerful
and fundamental concept of a variable is already difficult enough for beginning
students (in both computer science and algebra). Bytes and addresses do not
help the matter. In Python a variable is a name that refers to a thing. This
is a far more intuitive concept for beginning students and is much closer to the
meaning of “variable” that they learned in their math courses. I had much less
difficulty teaching variables this year than I did in the past, and I spent less
time helping students with problems using them.
2. from enclosing definitions, then globals, then builtins. enumerate(iterable)→ iterator returning tuples (index,value) from iterable
to current a and b. Example : a%=b ≈ a=a%b
Out-of-scope name → use the dotted attribute notation x.y (maybe Iterators Objects Interface
CONSOLE & INTERACTIVE INPUT/OUTPUT x.y.z.t)… where x is a name visible within the current scope.
next(self)→ next item1
print expression[,…] Class namespace → names defined in a class (class members).
__iter__(self)→ iterator object itself
input([prompt]) → evaluation of user input (typed data) Object namespace → names usable with object.name notation (attributes, 1
When reach end of collection, raise StopIteration exception on
raw_input([prompt]) → str: user input as a raw string methods). subsequent calls (ie. iterator usable only one time on a collection).
Direct manipulation (redefinition) of stdin/stdout/stderr via sys module :
Namespaces can be nested, inner namespaces hidding identical names Generators
sys.stdin sys.stdout sys.stderr from outer namespaces.
sys.__stdin__ sys.__stdout__ sys.__stderr__ Functions retaining their state between two calls. Return values using
dir([object]) → list: names defined in object namespace1
yield. Stop generation via simple return or via raise StopIteration.
All are files or files-like objects. The __xxx__ forms keep access to vars([object]) → dict2: identifier:value of object as a namespace1
1) build generator from function : gen=generatorfct(args)
original standard IO streams. if object not specified use nearest namespace (locals).
1
Ctrl-C raises KeyboardInterrupt exception. 2) use gen.next() values until StopIteration is raised.
must not be modified.
2
_ → value of last expression evaluation
Generator iterable expressions with : (x for x in iterable where cond)
Constants, Enumerations
help([object]) ® print online documentation
Use uppercase and _ for constants identifiers (good practice). May define Operations with/on Iterable
sys.displayhook → (rw) fct(value) called to display value namespaces to group constants. Cannot avoid global/local name
sys.__displayhook__ → backup of original displayhook function See Operations on Containers (p8).
redefinition (can eventually define namespaces as classes with
sys.ps1 → str: primary interpreter prompt attributes access control - not in Python spirit, and execution cost). See Iteration Tools (p9).
See third party modules pyenum for strict enum-like namespace.
sys.ps2 → str: secondary (continuation) interpreter prompt
INTERPRETATION / EXECUTION
FLOW CONTROL
See external package ipython for an enhanced interactive Python shell.
compile(string1,filename,kind2[,flags3[,dont_inherit3]]) → code object
OBJECTS, NAMES NAMESPACES eval(expression[,globals[,locals]]) → value: evaluation4 of expression string
AND Condition Loop
eval(code_object[,globals[,locals]]) → value: evaluation4 of code object
if cond : inst
Identifiers for var[,…] in iterable : inst
exec5 statements [in globals[,locals]] ® statements string1 executed4
[ elif cond : inst ]
Use : [a-zA-Z_][a-zA-Z0-9_]* [ else : inst ]
execfile(filename[,globals[,locals]])® file interpreted4
[ else : inst ]
Special usage for underscore :
while cond : inst
_xxx global not imported by import * 1
Multi-line statements in source code must use n as newline, and
There is no 'switch' or 'case'.
[ else : inst ]
_xxx implementation detail, for internal use (good practice) must be terminated by a newline.
Can use if elif elif… else.
__xxx 'private' class members, defined as _ClassName__xxx 2
Kind relative to string content, 'exec' → sequence of statements,
Exit loop with break.
Can use a mapping with
__xxx__ normally reserved by Python 'eval' → single expression, 'single' → single interactive statement.
functions bound to cases. Go to next iteration with continue.
Case is significant : This_Name != THIS_NAME. 3
Flags and dont_inherit are for future statements (see doc).
Loops else blocs only executed when 4
In context of globals and locals namespaces.
Objects and Names, Reference Counting loop exit normally (without break). 5
Exec is a langage statement, others are builtin functions.
Data are typed objects (all data), names are dynamically bound to Functions/methods exit
FUNCTIONS DEFINITIONS & USAGE
objects.
Exit function/method with return [value]
= assignment statement bind result of right part evaluation into left part
Exit from generator body with yield value def fctname([paramname[=defaultvalue][,…]] [,*args][,**kwargs]) :
name(s)/container(s). Examples :
Multiple returned values using tuple data. instructions
a = 3*c+5 a,b = (quot;Helloquot;,quot;Worldquot;) x,y,tabz[i] = fct(i)
Cannot yield within a try/finally block.
Parameters / Return value
s = quot;Helloquot; pi,e = 3.14,2.71 a,b = b,a
Exceptions Parameters are passed by references to objects.
When an object is no longer referenced (by names or by containers), it is
try : inst You can modify values of mutable objects types.
destroyed (its __del__ method is then called).
You cannot modify values of immutable objects types - as if they were
[, ]] : inst
except except_class value
[
sys.getrefcount(object)→ int: current reference counter of object passed by value.
…
Notation * → variable list of anonymous parameters in a tuple.
[ else : inst ]
Standard module weakref define tools to allow objects to be garbage
Notation ** → variable list of named parameters in a dict.
Can have a tuple of classes for except_class. Not specifying a class
collected when necessary and dynamically re-created on-demand.
Return value(s) with return [value[,…]]
catch all exceptions.
Mutable/Immutable Objects
Block else executed when try block exit normally. For multiple values, return a tuple. If no return value specified or if end
Mutable objects can be modified in place. Immutable objects cannot be
of function definition reached, return None value.
try : inst
modified (must build a new object with new value).
Lambda functions
Immutable : bool, int, long, float, complex, string, unicode, finally : inst
tuple, frozenset, buffer, slice. lambda param[,…] : expression
Process finally block in all execution paths (normal or exception).
Mutable : list, set, dict and other high level class objects. Anonymous functions defined inline. Result of expression evaluation is
raise exception_class[,value[,traceback]]
There is no constant definition. Just use uppercase names to identify returned (it must be an expression, no loop, no condition).
raise exception_object
symbols which must not be modified. Expression uses values known at definition time (except for params).
raise
Namespaces Callable Objects
Last form re-raise the currently catched exception in an exception
Places where Python found names. Objects having a __call__ method can be used as functions.
handler.
Builtins namespace → names from module __builtins__, already Methods bound to objects can be used as functions : f = o.meth
Iterable Protocol
available. callable(x) → bool: test x callable with x(…)
Generic and simple protocol allowing to iterate on any collection of data.
Global namespace → names defined at module level (zero indentation).
Objects of class defining __iter__ or __getitem__ are iterable (directly Calling Functions
Local namespace → names defined in methods/functions.
usable in for loops). [name=] fctname([expr[,…]][,name=expr[,…][,*args][,**args])
del name ® remove existing name from namespace (remove object binding)
__iter__(self) → iterator on self Anonymous parameters passed in parameters order declaration.
globals() → dict: identifier→value of global namespace
iter(object) → iterator on iterable object Params having default value can be omitted.
locals() → dict: identifier→value of local namespace
iter(callable,sentinel) → iterator returning callable() values up to sentinel Notation * → pass variable list of anonymous parameters in a tuple.
Current scope → names directly usable. Searched in locals, then locals
2a 2b 2c
3. Notation ** → pass variable list of named parameters in a dict. Object Life For copying, objects can define pickling protocol too (see Files -
Serialization - p12), in place of __copy__ and __deepcopy__.
__new__(classref,initargs…)→ object of classref type, already initialized1
Functions Control
Introspection
__init__ (self,initargs…)® called to initialize object with initargs
sys.getrecursionlimit()→ int: current recursion limit for functions
Beyond this documentation. Many __xxx___ attributes are defined,
__del__ (self)® called when object will be destroyed
sys.setrecursionlimit(limit) ® set recursion limit for functions
1
some are writable (see other docs).
If don't return a classref object, then object.__init__ is called with
Decorators
initargs. See standard module inspect to manipulate these data.
Glue code (functions) called at functions and methods definitions time,
Object Cast Example of Introspection Attributes
return the final function/method (generally with wrapping code).
@ ( __repr__(self)→ str: called for repr(self) and `self`
[ )]
decoratorname decorator_arguments […] Note: classes are objects too!
__str__(self) → str: called for str(self) and print self __base__ → list: parent classes of a class
def fct(fct_rguments):…
__coerce__(self,other) → value, called for coerce(self,other) __slots__ → tuple: allowed objects attributes names1 of a class
@dec1 @dec2(args) @dec3 def fct(…):…
like __class__ → class/type: object's class
fct = dec1(dec2(args)(dec3(fct)))) Object Hash Key
def fct(…):… ®
__dict__ → dict: defined attributes (object namespace) of an instance
See page PythonDecoratorLibrary in python.org Wiki for some decorators __hash__(self)→ int: hash code for object, used for hash(obj)and quick
__doc__ → string: documentation string of a package, module, class, function
mapping keys comparison - default implementation use hash(id(self))
definitions.
__name__ → str: object definition name of a function
TYPES/CLASSES & OBJECTS Attributes access
__file__ → string: pathname of loaded module .pyc, .pyo or .pyd
See also quot;Descriptors protocolquot; infra. 1
List of allowed attributes names. Usage discouraged.
All data are typed objects relying to classes.
__getattr__(self,name)→ value, called for undefined attributes
type(o) → type: type object of o
__getattribute__(self, name)→ value, always called
MODULES PACKAGES
Standard module types define type objects for builtins types. AND
__setattr__(self, name, value)® called for obj.name=value
Class Definition File gabuzo.py ® module gabuzo.
__delattr__(self, name)® called for del obj.name
class classname [(parentclass[,…])] : Directory kramed/ with a file __init__.py ® package kramed.
__hash__(self)→ int: 32 bits hash code, called for hash(obj) and dict
varname = expr ® varname defined in classname namespace Can have sub-packages (subdirectories having __init__.py file).
operations
def metname(self[,…]): ® define methods like functions Searched in the Python PATH.
__call__(self, *args, **kwargs)→ value, called for obj(…)
Support multiple inheritance. Can inherit from builtin class. Current Python PATH stored in sys.path list. Contains directories and
Static method / Class method
Inherit at least from object base class => Python 'new style class'. .zip files paths. Built from location of standard Python modules,
Use standard decorators (see Decorators p3).
First parameter of methods is target object, standard use self name. PYTHONPATH environment variable, directory of main module given on
class ClassName :
Access class members via class name, object members via self. command line, data specified in lines of .pth files found in Python home
@staticmethod directory, and data specified in registry under Windows.
This doc consider you use new style class (inheriting from object).
Current list of loaded modules stored in sys.modules map (main module
def methodname(…): …
Metaclass
is under key __main__).
@classmethod
Class definition create a new type. It can be done 'by hand' with :
def methodname(classref,…): … import module [as alias] [,…]
x = type('classname',(parentclass,[…]),{varname:expr[,…]}
from module import name [as alias] [,…]
Descriptors protocol
def metname(self[,…]):
from module import *
Descriptors are attribute objects controling access to attributes values.
x.metname = metname
reload(module) ® module is reloaded (but old references still on old module
They must define some of following methods :
This allow creation of metaclass classes (class building other class).
__get__(self,obj,ownerclass)→ attribute value for obj content)
Object Creation Import can use package path (ex:from encoding.aliases import…).
__set__(self,obj,value)® modify attribute in obj, set to value
obj = ClassName(initargs…) Direct import from a package use definitions from __init__.py file.
__delete__(self,obj)® remove attribute from obj
In cas of exception during initialization, object is destroyed when exiting Very careful with import * as imported names override names already
In these methods self is the descriptor object, and obj is the target
init code (reference counter reach zero). defined.
object which attribute is manipulated.
To limit your modules names exported and visible by import *, define
Classes & Objects Relations
Properties
module global __all__ with list of exported names (or use global
isinstance(obj,classinfo) → bool: test object of type/class classinfo
A descriptor to directly bind methods/functions to control attribute names _xxx).
issubclass(aclass, aparent) → bool: test same class or parent relationship
access. Use builtin type property with init args. See __import__ builtin function, imp builtin module and ihooks module.
Prefer isinstance() to type() for type checking.
class MyClass : __import__(modulename[, globals[,locals[,lnameslist]]])
Parent class methods are not automatically called if overriden in
attributename = property(getter,setter,deleter,description)
subclass - they must be explicitly called if necessary. Source encodings
Each init arg default to None (ie. undefined).
Call parent methods via super function : See PEP 263. Declare source files encoding in first or second line in a
Copying Objects
super(ThisClass,self).methodname(self,args…) special comment.
Assignment only duplicate references. To shallow copy an object (build a # * coding: encoding_name *
Or the old way, via parent class namespace :
new one with same values - referencing same content), or to deep copy If this is not specified, Python use sys.getdefaultencoding() value
ParentClass.methodname(self,args…)
an object (deep-copying referenced content), see object copy methods, (see modules sitecustomize.py and user.py).
Attributes Manipulation and functions in standard module copy. It is important to specify encoding of your modules as uquot;…quot; strings use
object.name = value copy.copy(object)→ value: shallow copy of object it to correctly build unicode literals.
setattr(object,name,value) ® object attribute set to value copy.deepcopy(object[[,memo],_nil])→ value: deep copy of object1 Special Attributes
Params memo and nil are used in recursive deepcopy, their default
object.name → value of object attribute 1
__name__ → str: module name, '__main__' for command-line called script
getattr(object,name[,default])→ value of object attribute values are None and empty list.
__file__ → string: pathname of compiled module loaded
del object.name Copy Protocol
MAIN EXECUTION / SCRIPT PARAMETERS
delattr(object,name) ® object attribute removed
__copy__(self)→ value: shallow copy of self, called by copy.copy(…)
Special Methods The 'main' module is the module called via command-line (or executed
__deepcopy__(self,memo)→ value: deep copy of self, called by
by shell with first script line #! /bin/env python).
Other special overridable __xxx___ methods are listed in respective
copy.deepcopy(…) Command-line parameters are available in sys.argv (a python list).
sections.
3a 3b 3c
4. BOOLEANS
At end of module, we may have : Comparison Overriding
if __name__=='__main__' :
__lt__(self, other)→ bool1 : called for self < other False : None, zero numbers, empty containers. False → 0.
# main code
__le__(self, other)→ bool1 : called for self <= other True : if not false. True → 1.
# generally call a 'main' function:
__gt__(self, other)→ bool1 : called for self > other bool(expr) → True | False
mainfunction(sys.argv[1:])
__ge__(self, other)→ bool1 : called for self >= other Logical not : not expr
# or in lib modules, execute test/demo code...
__eq__(self, other)→ bool1 : called for self == other Logical and : expr1 and expr2
Execution exit after last main module instruction (in multithread, wait
Logical or : expr1 or expr2
__ne__(self, other)→ bool1 : called for self != other
also for end of non-daemon threads), unless interactive mode is forced.
Logical and and or use short path evaluation.
and for self <> other
Can force exit with calling sys.exit(code), which raise a SystemExit
__cmp__(self,other)→ int : called for self compared to other, Bool Cast Overriding
exception - see Current Process - Exiting (p13).
self<other→value<0, self==other→value=0, self>other→value>0 __nonzero__(self) → bool : test object itself1
OPERATORS Any value usable as boolean value, or a NotImplemented value if
1 1
If __nonzero__ undefined, look at __len__, else object is true.
Deal with arithmetic, boolean logic, bit level, indexing and slicing. cannot compare with such other type.
NUMBERS
Priority Operators as Functions
Builtin integer types : int (like C long), long (unlimited integer)
1 (a,…) [a,… 6 x+y 11 x<y x<=y x>y x>=y x==y x!=y Operators are also defined as functions in standard operator module.
]
int(expr[,base=10]) → int: cast of expr
{a:b,… `… xy x<>y x is y x is not y x in s
`
} Comparison
long(expr[,base=10]) → long: cast of expr
x not in s
lt(a,b) = __lt__(a,b) ne(a,b) = __ne__(a,b) Builtin floating point types : float (like C double), complex (real and
2 s[i] s[i:j] 7 x<<y 12 not
x
le(a,b) = __le__(a,b) ge(a,b) = __ge__(a,b) imaginary parts are float).
x>>y
s.attr f(…) float(expr) → float: representation of expr
eq(a,b) = __eq__(a,b) gt(a,b) = __gt__(a,b)
13 x and y
3 +x x ~x 8 x&y
complex(x[,y]) → complex: number: x+yj
Logical / Boolean
[x+]yj → complex: number, ex: 3+4j -8.2j
4 x**y 9 x^y 14 x or y
not_(o) = __not__(o) and_(a,b) = __and__(a,b)
c.real → float: real part of complex number
5 x*y x/y x%y 10 x|y 15 lambda :expr truth(o) or_(a,b) = __or__(a,b)
args
c.img → float: imaginary part of complex number
is_(a,b) xor(a,b) = __xor__(a,b)
Arithmetic Operators c.conjugate() → complex: conjugate of complex number (real,-img)
is_not(a,b)
Can be defined for any data type. Maximum int integer in sys.maxint.
Arithmetic Automatic conversions between numeric types.
Arithmetic Overriding
Automatic conversions from int to long when result overflow max int.
abs(o) = __abs__(o) truediv(a,b) = __truediv__(a,b)
__add__(self,other) → value: called for self + other Direct conversions from/to strings from/to int, long… via types
add(a,b) = __add__(a,b) floordiv(a,b) = __floordiv__(a,b)
__sub__(self,other) → value: called for self other constructors.
sub(a,b) = __sub__(a,b) neg(o) = __neg__(o) Type Decimal defined in standard module decimal.
__mul__(self,other) → value: called for self * other
mul(a,b) = __mul__(a,b) pos(o) = __pos__(o) Base fixed type compact storage arrays in standard module array.
__div__(self,other) → value: called1 for self / other
div(a,b) = __div__(a,b) pow(a,b) = __pow__(a,b)
__truediv__(self,other) → value: called2 for self / other Operators
mod(a,b) = __mod__(a,b)
__floordiv__(self,other) → value: called for self // other x +x x+y xy x*y x/y 1 x//y 1 x%y 2 x**y 2
Bit Level
With from __future__ import division, / is true division (1/2→0.5),
__mod__(self,other) → value: called for self % other
1
lshift(a,b) = __lshift__(a,b) and // is floor division (1//2→0). Else for integers / is still floor division.
__divmod__(self,other) → value: called for divmod(self,other)
rshift(a,b) = __rshift__(a,b) % is remainder operator, ** is power elevation operator (same as pow).
2
__pow__(self,other) → value: called for self ** other
inv(o) = invert(o) = __inv__(o) = __invert__(o)
__nonzero__(self)→ value: called for nonzero(self) Functions
Sequences Some functions in builtins.
__neg__(self) → value: called for self
abs(x) → absolute value of x
concat(a,b) = __concat__(a,b)
__pos__(self) → value: called for +self
divmod(x,y) → (x/y,x%y)
contains(a,b) = __contains__(a,b)
__abs__(self) → value: called for abs(self)
oct(integer) → str: octal representation of integer number
countOf(a,b)
__iadd__(self,other) ® called for self += other
hex(integer) → str: hexadecimal representation of integer number
indexOf(a,b)
__isub__(self,other) ® called for self = other
repeat(a,b) = __repeat__(a,b) Math Functions
__imul__(self,other) ® called for self *= other
setitem(a,b,c) = __setitem__(a,b,c) Standard floating point functions/data in standard math module.
__idiv__(self,other) ® called1 for self /= other
getitem(a,b) = __getitem__(a,b) acos(x) → float: radians angle for x cosinus value : [-1…1] →[0…π]
__itruediv__(self,other) ® called2 for self /= other
delitem(a,b) = __delitem__(a,b) asin(x) → float: radians angle for x sinus value : [-1…1] →[-π/2…+π/2]
__ifloordiv__(self, other) ® called for self //= other
setslice(a,b,c,v) = __setslice__(a,b,c,v) atan(x) → float: radians angle for x tangent value : [-∞…∞] →]-π/2…+π/2[
__imod__(self,other) ® called for self %= other
getslice(a,b,c) = __getslice__(a,b,c) atan2(x,y) → float: randians angle for x/y tangent value
__ipow__(self,other) ® called for self **= other
delslice(a,b,c) = __delslice__(a,b,c)
1
without / 2 with from __futur__ import division ceil(x) → float: smallest integral value >= x
Binary operators __xxx__ have also __rxxx__ forms, called when Type Testing cos(x) → float: cosinus value for radians angle x
target object is on right side.
cosh(x) → float: hyperbolic cosinus value for radians angle x
These functions must be considered as not reliable.
Comparison Operators isMappingType(o) exp(x) → float: exponential of x = ex
Operators can compare any data types. isNumberType(o) fabs(x) → float: absolute value of x
Compare values with < <= > >= == != <>. isSequenceType(o) floor(x) → float: largest integral value <= x
Test objects identity with is and is not (compare on id(obj)). fmod(x,y) → float: modulo = remainder of x/y
Attribute and Item Lookup
Direct composition of comparators is allowed in expressions : x<y<=z>t. frexp(x) → (float,int): (m,y) m mantissa of x,y exponent of x — where
attrgetter(attr) → fct: where fct(x)→x.attr
Builtin function cmp(o1,o2) → 1 (o1 < o2), 0 (o1 == o2), 1 (o1 > o2) x=m*2y
itemgetter(item) → fct: where fct(x)→x[item] ldepx(x,i) → x * (2**i)
4a 4b 4c