Python Fundamentals Sheet
Python Fundamentals Sheet
Python Fundamentals Sheet
Where is python used? → Web Frameworks, Scientific Computing, Image Processing, Databases,
Build Systems, Documentation, Persistence, Math, Operating System, Crypography, Concurrency Web
Protocols.
Python is powerful, popular and open-source. Because of that it is accessible! This course is Example
driven, it features 10 modules :
1. Getting Started
2. Strings and Collections
3. Modularity
4. Built-in Types and the Object Model
5. Collection Types
6. Handling Exceptions
7. Comprehensions, Iterables and Generators
8. Defining new types with Classes
9. Files and Resource management
10. Shipping Working and maintainable Code
Python Overview : → Guido von Rossum – Benevolent Dictator for Life; Open-source project; General
Purpose Programming Language; Clear, readable == Expressive and Powerful; Different Python
implementations CPython – written in C; Jython, Iron Python, RPython; Two major versions Python2
and Python3. The Bytecode is invisible so the python is called interpreted language, which isn't true in
full. Python has a lot of modules, it is said that Python is “Batteries included” language. Python is also
a philosophy about writing code. - Pythonic Code; import this – Zen of Python.
Strongly and Dynamically Typed.
Zen Moment
Readability counts. Clarity matters, so readability makes, for valuable code.
Chapter Summary:
– obtaining and installing python3
– read-eval-print-loop or REPL
– simple arithmetic with +- */ % and //
– Assigning objects to named variables with the = operators
– print()
– Exiting the REPL → CTRL-Z on Windows and CTRL-D on Linux
– Significant Indentation – usually four spaces
– Python Enhancement Proposals
- PEP 8 – Python Style Guide
- PEP 20 – The Zen of Python
– Importing Python Standard Library modules: all three forms
– Finding and browsing help()
– scalar built-in types → int float None bool and conversion between types
– Relational operators for equivaalence and ordering
– conditional statements with if... elif... else
– while loops
– interrupting execution with CTRL-C to create a KeyboardInterrupt exception
– Breaking out of loops with break
– Augmented assignment operators for modifying objects in-place
– requesting text from the user with input()
Chapter 3 – Strings and Collections
Practicality beats purity → Beautiful text strings rendered in literal form - simple elegance
strings are sequence types so we can use ceratain operation on them; no separate character type >
characters are simply one-element strings; strings are immutable; help(str); python strings are Unicode
bytes – immutable sequences of bytes; similar to strings but used for binary data
b'data' → byte literal
there is bytes constructor but it is advanced
Zen Moment
Practicality beats purity. Beautiful text strings. Rendered in literal form. Simple elegance.
decode
=>str------
|… |
--bytes<=
bytes is a sequence of bytes and strings are sequences of unicode codepoints and that's why we use
encode and decode
Chapter 4 Modularity
def – used to make functions; return keyword; functions without return returns None, but we don't
represent None so we don't see anything; REUSABLE functions;
distinguishing between module import and module execution***
special attributes in python are delimited by double underscores; __name__ evaluetes to “__main__” or
the actual module name depending on how the enclosing module is being used; module code is only
executed once on first import **; python execution model → When are functions defined, What
happens when python module is imported;
advanced command line argument parsing: python standard library → argparse or many third party
options such as → docopt
documenting your code using docstrings
“”” put below functions“””
Zen Moment
Sparse is better than dense. Two between the functions, that is the number of lines, PEP8 recommends.
Chapter Summary:
Chapter 5 Objects
variables are references to objects; integer objects are immutable; y = x; no copy of data, just copy of
reference; id() → returns a unique indentifier for an object; garbage collectio; id() deals with the object
not the reference; Variables are named references to objects***; value equality vs identity; value –
equivalent “contents”; identity – same objects; value comparison can be controlled programatically;
pass by object reference(arguments) → the value of the reference is copied not the value of the object.
Default arguments; def function(a, b=value) → keyword and positional arguments; default argument
values are evaluated when def is evaluated. They can be modified like any other object; Python –
dynamic and strong typing; Javascript – dynamic and weak typing;
Type systems:
dynamic type system – object types are only resolved at runtime
strong type system – there is no implicit type conversion
Zen Moment
Special cases aren't special enough to break the rules. We follow patterns, not to kill complexity, but to
master it.
variable scoping → object references have no type; scopes are contexts in which named references can
be looked up; local → inside a current function; enclosing → any and all enclosing functions;
global → top level of module
built-in → provided by the builtins module
LEGB rule → names are looked in narrowest path; global → rebinds a global name at module scope
In Python, everything is an OBJECT.; type(); dir(object) → used to see attributes of an object
Chapter Summary:
Chapter 6 Collections
tuple – heterogeneous immutable sequence ( ) ; tuples can contain any type of object, nested tuples; k =
(391, ) → single element tuple; tuple unpacking → useful
strings – homogeneous immutable sequence of unicode codepoints(characters); len(). /join split
partition format etc.
range → arithmetic progression of integers; prefer enumerate() for counters
list → heterogeneous mutable sequence; slicing, full slice [:] → used for copying a list; index(item), del
seq[index], insert, reverse() reversed() sort() sorted()
shallow copies*** → list repetition is shallow
dictionary → unordered mapping from unique immutable keys to mutable values; dict() constructor
accepts: iterable series of key-value 2-tuples ; d.copy() → for copying dictionaries; dict(d) → pass
existing dictionary to dict(); extend a dictionary with update(); .values .keys
pprint module → pretty printing
set → unordered collection of unique immutable objects; {} to create empty set use set() constructor;
membership → in and not in; set algebra operations(unions, etc); s.union/intersection/difference etc.
Collection Protocols: - protocol implementing collections
protocols → to implement a protocol bjects must support certain operations; most collections
implement a container, sized and a iterable
container → in and not in
sized → len()
iterable → can produce an iterator with iter(s)
sequence → retrieve elements by index
Zen Moment
The way may not be obvious at first. To concatenate, invoke join on empty text. Something for nothing.
Chapter Summary:
exception handling is a mechanism for stopping “normal” program flow and continuing at some
surrounding context or code block
raise an exception to interrupt program flow → handle an exception to resume control → unhandled
exceptions will terminate the program → exception objects contain information about the exceptional
event; exceptions and control flow; different programming errors**;
IMPRUDENT → not showing care for consequences of an action; rash;
Caller need to know what exceptions to expect and when; use exceptions that users will anticipate;
standard exceptions are always the best choice; exceptions are parts of families of related functions that
are referred to as “protocols”; use common or existing exception types when possible; avoid protecting
against TypeError; Easier to ask forgiveness than permissions → in favor vs look before you leap
resource cleanup with finally → try...finally lets you clean up wheter an exception occurs or not
Errors are like bells, and if we make them silent they are of no use
platform specific modules → Windows – msvcrt, Linux/osX → sys, tty, termios
Chapter Summary:
– raising an exception interrupts normal program flow and transfers control to an exception
handler
– exception handlers defined using the try...except construct
– try blocks define a context for detecting exceptions
– corresponding except blocks handle specific exception types
– python uses exceptions pervasively
– many built-in language features depend on them
– except blocks can capture an exception which are often of a standard type
– programmer errors should not normally be handled
– exceptional conditions can be signaled using raise
– raise without an argument re-raises the current exception
– generally do not check for TypeErrors
– Exception objects can be converted to strings using str()
– A functions exceptions for part of its API
– the should be documented properly
– prefer to use built-in exception types when possible
– use the try...finally construct to perform cleanup actions
– may be used in conjuction with except blocks
– Output of print() can be redirected using the optional file argument
– use and and or for combining boolean expressions
– return codes are too easily ignored
– platform-specific actions can be implemented using EAFP along with catching ImportErrors
Chapter 8 Iterables
Iterable Objects**; comprehensions → concise syntax for describing lists, sets or dictionaries in
declarative or functional style; list comprehensions [len(word) for word in words]; set comprehensions
{expr(item) for item in iterable}; dictionary comprehensions{key_expr:value_expr for item in iterable}
dont cram too much complexity into comprehensions; [x for x in range(101) if is_prime(x)] → filtering
predicates?* ; optional filtering clause [expr(item) for item in iterable if predicate(item)]; code is
written once but read over and over. Fewer is clearer but don't overuse comprehensions; iteration
protocols → iterable protocol; iterator protocol;
Iterable protocol → Iterable objects can be passed to the built-in iter() function to get an iterator;
iterator = iter(iterable)
Iterator protocol → iterator objects can be passed to the built-in next() function to fetch the next item
item = next(iterator)
generator functions → those that have at least one yield → most powerful feature in language
Generator functions in Python → specify iterable sequences; all generators are iterators
are lazily evaluated → the next value in the sequence is computed on demand; are composable into
pipelines → for natural stream processing; yield keyword; next(s) → next value;
Stateful Geneartors
– generators resume execution
– can maintain state in local variables
– complex control flow
– lazy evaluation
Laziness and the Infinite
– Just in Time computation
– Infinite or large sequences → sensor readings, mathematical series, massive files
Generator comprehensions
– similar syntax to list comprehensions
– create a generator objec
– concise
– lazy evaluation
(expr(item) for item in iterable)
Batteries included → Iteration Tools → itertools
Chapter Summary:
– Comprehensions
– Comprehensions are a concise syntax for describing lists, sets, and dictionaries
– Comprehensions operate on an iterable source object and apply an optional predicate filter and
a mandatory expression, both of which are usually in terms of the current item
– iterables are objects over which we can iterate item by item
– we retrieve an iterator from an iterable object using the built-in iter() function
– Iterators produce items one-by-one from the underlying iterable series each time they are passed
to the built-in next() function
– Generators
– Generator functions allow us to describe series using imperative code
– Generator functions contain at least one use of the yield keyword
– Generators are iterators. When advanced with next() the generator starts or resumes execution
up to and including the next yield
– each call to generator function creates a new generator object
– Generators can maintain explicit state in local variables between iterations
– Generators are lazy, and so can model infinite series of data
– Generator expressions have a similar syntactic form to list comprehensions and allow for a
more declarative and concise way of creating generator objects
– Iteration tools – Built-ins such as sum() any() zip() all() min() max() enumerate()
– Standard library itertools module – chain() islice() count() and many more!
Chapter 9 Classes
You can get a long way with python's built-in types; but when they're not right for the job, you can use
classes to create custom types; Classes define the structure and behaviour of objects; An object's class
controls its initialization; Classes make complex problems tractable. Classes can make simple solutions
overly complex; Python lets you find right balance; Class Names use CamelCase; Method → function
defined with a class; Instance method → functions which can be called on objects; self → the first
argument to all instance methods; f = Flight(); f.number == Flight.number(f);
Initializers; __init__() → instance method for initializing new objects → is an initializer not a
constructor; self is similar to “this” in java or c++; implementation details start with _
public, private, protected*** → we're all adults here...
Class invariants** → truths about an object that endure for its lifetime
Law of Demeter → Never call methods on objects you get from other calls. Only talk to your friends.
Zen Moment
Complex is better than complicated. Many moving parts combined in a clever box are now one good
tool.
Dont feel compelled to create classes without good reason. Tell objects what to do, don't ask for their
state and base your actions on that.; \ → used for breaking long lines of code;
Polymorphism → using objects of different types through a common interface
DuckTyping → When I see a bird that walks like a duck and swims like a duck and quack like a duck, I
call that bird a duck. - James William Riley
Inheritance – A sub-class can derive from a base-class, inheriting its behaviour and making behaviour
specific to the Sub-class. → python uses late binding.
In Python, inheritance is most useful for sharing implementation.
Chapter Summary:
open() → open a file, mode and encoding; text file access → is encoded; sys.getdefaultencoding()
open() → modes**; write() → returns the number of codepoints not the number of bytes
read(bytes); seek(offset); readline(), writelines(); files as iterators; Typical file usage:
f = open()
# work work work
f.close() → is required to actually write the data
with-block → resource cleanup with context-managers
open() - returns a context-manager
Chapter Summary:
– Files are opened usng the built-in open() function which accepts a file mode to control
read/write/append behaviour and wheter the file is to be treated as raw binary or encoded text
data
– For text data you should specify a text encoding
– text files deal with string objects and perform universal newline translation and string encoding
– binary files deal with bytes objects with no newline translation or encoding
– when writing files, it's our responsibility to provide newline characters for line breaks
– files should always be closed after use
– files provide various line-oriented methods for reading and are also iterators which yield line by
line
– files are context managers and the with-statement can be used with content managers to ensure
that cleanup operations, such as closing files are performed
– The notion of file-like objects is loosely defined, but very useful in practice
– Exercise EAFP to make most of them
– Context managers aren't restricted to file-like-objects. We can use tools in the contextlib
standard library module, such as closing() wrapper to create our own context managers
– help() can be used on instance objects, not just types
– Python supports bitwise operators &, | and left and right-shifts.
Zen Moment
In the face of ambiguity, refuse the temptation to guess. To guess is to know, that you have left
something out. What are you missing?
Chapter Summary :
packages → a module which can contain other modules → adding structure to program; module →
single source code file; packages are generally directories; urllib.__path__ ; sys.path → list of
directories Python searches for modules; sys.path.append(' '); PYTHONPATH – Environment variable
listing; paths added to sys.pat; export PYTHONPATH=' '; reader.__file__ ; subpackaging →
python3 – m reader.compressed.gzipped test.gz data compressed with gzip
Package review
1. Packages are modules that contain other modules
2. Packages are generally implemented as directories containing a special __init__.py file
3. The __init__.py file is executed when the package is imported
4. Packages can contain subpackages which themselves are implemented with __init__.py files in
directories; absolute imports; relative imports → imports which use a relative path to moduless
in the same package
. → same directory ; .. → parent directory ; Relative imports :
1. Can reduce typing in deeply nested package structures
2. Promote certain forms of modifiability
3. Can aid package renaming and refactoring
4. General advice is to avoid them in most cases
__all__ - list of attribute names imported via from module import *
locals() → looks which modules are imported in interpreter; from module import * → The __all__
attribute should be a list of strings containing names available in the module; → protecting imports
– namespace packages-> packages split across several directories → useful for splitting large
packages into multiple parts PEP420; namespace packages have no __init__.py → this avoids
complex initialization ordering problems; How does python find namespace packages? :
1. Python scans all entries in sys.path
2. If a matching directory with __init__.py is found a normal package is loaded
3. Otherwise, all matching directories in sys.path are considered part of the namespace package
executable directories → directories containing an entry point for Python execution; executable
zip files → zip file containing and entry point for Python execution; singleton pattern; modules
as singleton; recommended project structure :
Chapter Summary:
Function review; functions → module global scope; methods → class arguments; default argument
value; function objects are callable objects; Callable instances : __call__(); timeit module →
functions(math) that save states in between calls; Classes are callable → calling the class invokes the
constructor; Conditional expressions → PEP308 Lambdas → Alonzo Church → lambda is expression
which results in callable object;
def :
Lambdas :
Detecting callable objects BIF callable(); extended formal argument syntax → formal arguments;
argumetns at the function definition site(*args) positional arguments; keyword arguments(**kwargs);
Extended call syntax → extended actual argument syntax; actual arguments → arguments at the
function call site; Forwarding arguments; pprint module; Transposition***;
Chapter Summary:
Chapter 3 Closures and Decorators
Local Functions → define functions inside functions; LEGB rule; useful for: specialized one-off
functions, aid in code organization and readability; similar to lambdas but more general; may contain
multiple expressions, may contain statements; returning functions from functions → first class
functions; functions can be treated like any other object; clojures and nested scopes → closures –
maintain references to objects from earlier scopes; function factories → functions that returns new
specialized functions → combination of runtime function definition and clojures makes this possible
The nonlocal keyword → LEGB does not apply when making new bindings; global – introduce names
from global namespace into local namespace; you get a syntax error if name doesn't exists; function
decorators → missing; A first decorator example @escape_unicode; what can be a decorator? → we've
seen functions as decorators, but other objects can be decorators as well; class decorators; instance as
decorators → decorating with instance calls the instance; multiple decorators; @ => on separate line
above function → processed in reverse order; Decorating methods; functools.wrap() → naive decorator
can lose important metadata; properly update metadata on wrapped functions → functools library;
decorators are powerful tool, widely used in python; don't overuse decorators!;
Chapter Summary:
Chapter 4 Properties and class methods
str(), repr() → Two string representation functions for making string representations from Python
object __str()__ and __repr()__; repr() → BIF that produces an unambigous string representation of an
object → repr() → representation; exactness is more important than human friendliness; suited for
debugging; includes identifying infomration; generally best for logging more info than str; repr is for
developers; str is for clients; import pdb; as a rule you should always write a repr() for your classes;
default rpr is not very helpful; str() → human friendly representation of an object; not programmer
oriented; str() is constructor fo str type(); when are the representations used → print uses str by default,
str() simply calls repr() but repr() doesn't call str(); repr() is used when showing elements of a
collection; Interaction with format() → special __format__ method; reprlib → supports alternative
implementations of repr(); ascii(), ord() and chr() → ascii replaces non ascii characters with escape
sequences, ord() → converts a single character to its integer Unicode point; chr() → takes integer
codepoint and returns unicode character
Chapter Summary:
reviewing the int and float; sys.float_info(); decimal module and the decimal type; rational numbers
with fraction types, complex type and the cmath module; → complex numbers; built in numeric
functions abs() and rand(); abs() gives distance from zero; round() - performs decimal rounding for all
scalar number types; number base conversions → bin(), oct(), hex(); the datetime module and date type
=> date, time, datetime, timedelta, timezone; the time type, the datetime type; timedelta → durations
with the timedelta type; arithmetic with datetime, timezones;
Chapter Summary:
Multi input comprehensions → comprehensions → short-hand syntax for creating collections and
iterable objects → lists, dicts, set, generators → comprehensions can use multiple input sequences and
multiple if clauses; container populated “atomically” → allows python to optimize creation; more
readable; nested comprehensions → comprehensions can bbe nested inside other comprehensions;
the map() function → apply a function to every element in a sequence, producing a new sequence
map(ord, string) ; multiple input sequences → map() can accept any number of input sequences → the
number of input sequences must match the number of function arguments; map() vs comprehensions;
The filter() fucntion → apply a function to each element in a sequence, constructing a new sequence
with the elements with the elements for which the function returns True; the functools.reduce() -
repeatedly apply a function to the elements of a sequence, reducing them to a single value → function
prgoramming fold c++ STL ::accumulate(); optional initial value is conceptually just added to the start
of the input sequence; combining map() and reduce() → map-reduce algorithm; Iteration protocols;
iter() - create an iterator; next() - get next element in a sequence; StopIteration – signal the end of the
sequence; iterable – an object which implements __iter__() method; iterator – an object which
implements the iterable protocol and which implements the __next__ method; putting the protocols
together; alternative iterable protocol → works with any object that supports consecutive integer
indexing via __getitem__(); extended iter() format → iter(callable, sentinel); extended iter() is often
used for creating infinite sequences from existing functions.
Chapter Summary:
Chapter 8 Inheritance and Subtype Polymorphism
Chapter Summary:
collection protocol overview → collections, tuple, str, range, list, dict, set; → to implement a protocol
objects must support certain operations; most collections implement container sized and iterable; all
except dict and set are sequences; collection construction → TDD, test code design(refactor) – the
construction connection; the container protocol __contains__(item); the sized protocol - __len__(); the
iterable protocol __iter__(); the sequence protocol slicing; comprehensible test results with __repr__()
implementing equality and inequality; equality vs identity test; the sequence protocol reversing; the
sequence protocol index(); the sequence protocol count(); improving performance rom O(n) to O(log n)
Refactoring to avoid DRY – Dont Repeat Yourself; Checking Protocol Implementation; The sequence
protocol concatenation and repetition; the set protocol;
Chapter Summary:
Always specify an exception type → avoid bad practices in python, exception handling; The Standard
Exception hierarchy → exceptions are arranged in an inheritance hierarchy; exception payloads;
defining new exceptions; chaining exceptions; traceback objects; assertions internal invariants;
assertions class invariants; assertions performance;
Chapter Summary: