Python 101 - Introduction To Python
Python 101 - Introduction To Python
Python 101 - Introduction To Python
Revision: 1.1a
Date: October 05, 2014
Copyright: Copyright (c) 2003 Dave Kuhlman. All Rights Reserved. This software is
subject to the provisions of the MIT License
http://www.opensource.org/licenses/mit-license.php.
Abstract: This document is a self-learning document for a first course in Python
programming. This course contains an introduction to the Python
language, instruction in the important and commonly used features of
the language, and practical exercises in the use of those features.
Contents
1 Introductions Etc
1.1 Resources
1.2 A general description of Python
1.3 Interactive Python
2 Lexical matters
2.1 Lines
2.2 Comments
2.3 Names and tokens
2.4 Blocks and indentation
2.5 Doc strings
2.6 Program structure
2.7 Operators
2.8 Also see
2.9 Code evaluation
3 Statements and inspection -- preliminaries
4 Built-in data-types
4.1 Numeric types
4.2 Tuples and lists
4.3 Strings
4.3.1 The new string.format method
4.3.2 Unicode strings
4.4 Dictionaries
4.5 Files
4.6 Other built-in types
4.6.1 The None value/type
4.6.2 Boolean values
4.6.3 Sets and frozensets
5 Functions and Classes -- A Preview
6 Statements
6.1 Assignment statement
6.2 import statement
6.3 print statement
6.4 if: elif: else: statement
http://www.davekuhlman.org/python_101.html 1/81
11/17/2017 Python 101 --- Introduction to Python
6.5
for: statement
6.6
while: statement
6.7
continue and break statements
6.8
try: except: statement
6.9
raise statement
6.10with: statement
6.10.1 Writing a context manager
6.10.2 Using the with: statement
6.11 del
6.12 case statement
7 Functions, Modules, Packages, and Debugging
7.1 Functions
7.1.1 The def statement
7.1.2 Returning values
7.1.3 Parameters
7.1.4 Arguments
7.1.5 Local variables
7.1.6 Other things to know about functions
7.1.7 Global variables and the global statement
7.1.8 Doc strings for functions
7.1.9 Decorators for functions
7.2 lambda
7.3 Iterators and generators
7.4 Modules
7.4.1 Doc strings for modules
7.5 Packages
8 Classes
8.1 A simple class
8.2 Defining methods
8.3 The constructor
8.4 Member variables
8.5 Calling methods
8.6 Adding inheritance
8.7 Class variables
8.8 Class methods and static methods
8.9 Properties
8.10 Interfaces
8.11 New-style classes
8.12 Doc strings for classes
8.13 Private members
9 Special Tasks
9.1 Debugging tools
9.2 File input and output
9.3 Unit tests
9.3.1 A simple example
9.3.2 Unit test suites
9.3.3 Additional unittest features
9.3.4 Guidance on Unit Testing
9.4 doctest
9.5 The Python database API
9.6 Installing Python packages
10 More Python Features and Exercises
1 Introductions Etc
Introductions
http://www.davekuhlman.org/python_101.html 2/81
11/17/2017 Python 101 --- Introduction to Python
Running scripts
Editors -- Choose an editor which you can configure so that it indents with 4 spaces,
not tab characters. For a list of editors for Python, see:
http://wiki.python.org/moin/PythonEditors. A few possible editors:
SciTE -- http://www.scintilla.org/SciTE.html.
MS Windows only -- (1) TextPad -- http://www.textpad.com; (2) UltraEdit --
http://www.ultraedit.com/.
Jed -- See http://www.jedsoft.org/jed/.
Emacs -- See http://www.gnu.org/software/emacs/ and
http://www.xemacs.org/faq/xemacs-faq.html.
jEdit -- Requires a bit of customization for Python -- See http://jedit.org.
Vim -- http://www.vim.org/
Geany -- http://www.geany.org/
And many more.
Interactive interpreters:
python
ipython
Idle
1.1 Resources
Where else to get help:
FAQs -- http://www.python.org/doc/faq/.
http://www.davekuhlman.org/python_101.html 3/81
11/17/2017 Python 101 --- Introduction to Python
Other python related mailing lists and lists for specific applications (for
example, Zope, Twisted, etc). Try: http://dir.gmane.org/search.php?
match=python.
Local documentation:
At the interactive prompt, use help(obj). You might need to import it first.
Example:
In [13]: open?
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form: <built-in function open>
Namespace: Python builtin
Docstring:
open(name[, mode[, buffering]]) -> file object
Python uses indentation to show block structure. Indent one level to show the
beginning of a block. Out-dent one level to show the end of a block. As an
example, the following C-style code:
if (x)
{
if (y)
{
f1()
}
f2()
}
if x:
if y:
f1()
f2()
And, the convention is to use four spaces (and no hard tabs) for each level of
indentation. Actually, it's more than a convention; it's practically a requirement.
http://www.davekuhlman.org/python_101.html 5/81
11/17/2017 Python 101 --- Introduction to Python
Following that "convention" will make it so much easier to merge your Python code
with code from other sources.
An overview of Python:
A scripting language -- Python is suitable (1) for embedding, (2) for writing
small unstructured scripts, (3) for "quick and dirty" programs.
Not a scripting language -- (1) Python scales. (2) Python encourages us to write
code that is clear and well-structured.
Provides an interactive command line and interpreter shell. In fact, there are
several.
Reasonably high level -- High level built-in data types; high level control
structures (for walking lists and iterators, for example).
Explicitness
First-class objects:
Definition: Can (1) pass to function; (2) return from function; (3) stuff
into a data structure.
Operators can be applied to values (not variables). Example: f(x)[3]
Indented block structure -- "Python is pseudo-code that runs."
http://www.davekuhlman.org/python_101.html 6/81
11/17/2017 Python 101 --- Introduction to Python
In some cases, SWIG can generate wrappers for existing C/C++ code
automatically. See http://www.swig.org/
Cython enables us to generate C code from Python and to "easily" create
wrappers for C/C++ functions. See
http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
To embed and extend Python with Java, there is Jython. See
http://www.jython.org/
Automatic garbage collection. (But, there is a gc module to allow explicit control
of garbage collection.)
Varieties of Python:
The migration tool, 2to3, eases the conversion of 2.x code to 3.x.
If you execute Python from the command line with no script (no arguments), Python
gives you an interactive prompt. This is an excellent facility for learning Python and
for trying small snippets of code. Many of the examples that follow were developed
using the Python interactive prompt.
Start the Python interactive interpreter by typing python with no arguments at the
command line. For example:
$ python
Python 2.6.1 (r261:67515, Jan 11 2009, 15:19:23)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> print 'hello'
hello
>>>
You may also want to consider using IDLE. IDLE is a graphical integrated
development environment for Python; it contains a Python shell. It is likely that Idle
was installed for you when you installed Python. You will find a script to start up IDLE
in the Tools/scripts directory of your Python distribution. IDLE requires Tkinter.
In addition, there are tools that will give you a more powerful and fancy Python
interactive interpreter. One example is IPython, which is available at
http://ipython.scipy.org/.
2 Lexical matters
2.1 Lines
Python does what you want it to do most of the time so that you only have to
add extra characters some of the time.
Statement separator is a semi-colon, but is only needed when there is more
than one statement on a line. And, writing more than one statement on the
same line is considered bad form.
Continuation lines -- A back-slash as last character of the line makes the
following line a continuation of the current line. But, note that an opening
"context" (parenthesis, square bracket, or curly bracket) makes the back-slash
unnecessary.
2.2 Comments
Everything after "#" on a line is ignored. No block comments, but doc strings are a
comment in quotes at the beginning of a module, class, method or function. Also,
editors with support for Python often provide the ability to comment out selected
blocks of code, usually with "##".
http://www.davekuhlman.org/python_101.html 8/81
11/17/2017 Python 101 --- Introduction to Python
Allowed characters: a-z A-Z 0-9 underscore, and must begin with a letter or
underscore.
Names and identifiers are case sensitive.
Identifiers can be of unlimited length.
Special names, customizing, etc. -- Usually begin and end in double
underscores.
Special name classes -- Single and double underscores.
Single leading single underscore -- Suggests a "private" method or
variable name. Not imported by "from module import *".
Single trailing underscore -- Use it to avoid conflicts with Python
keywords.
Double leading underscores -- Used in a class definition to cause name
mangling (weak hiding). But, not often used.
Naming conventions -- Not rigid, but:
Modules and packages -- all lower case.
Globals and constants -- Upper case.
Classes -- Bumpy caps with initial upper.
Methods and functions -- All lower case with words separated by
underscores.
Local variables -- Lower case (with underscore between words) or bumpy
caps with initial lower or your choice.
Good advice -- Follow the conventions used in the code on which you are
working.
Names/variables in Python do not have a type. Values have types.
Reduces the need for a coding standard. Only need to specify that indentation is
4 spaces and no hard tabs.
Reduces inconsistency. Code from different sources follow the same indentation
style. It has to.
Reduces work. Only need to get the indentation correct, not both indentation
and brackets.
Reduces clutter. Eliminates all the curly brackets.
If it looks correct, it is correct. Indentation cannot fool the reader.
Editor considerations -- The standard is 4 spaces (no hard tabs) for each indentation
level. You will need a text editor that helps you respect that.
A doc string is written as a quoted string that is at the top of a module or the first
lines after the header line of a function or class.
http://www.davekuhlman.org/python_101.html 9/81
11/17/2017 Python 101 --- Introduction to Python
We can use triple-quoting to create doc strings that span multiple lines.
There are also tools that extract and format doc strings, for example:
See the following for suggestions and more information on doc strings: Docstring
conventions -- http://www.python.org/dev/peps/pep-0257/.
2.7 Operators
See: http://docs.python.org/ref/operators.html. Python defines the following
operators:
+ - * ** / // %
<< >> & | ^ ~
< > <= >= == != <>
The comparison operators <> and != are alternate spellings of the same
operator. != is the preferred spelling; <> is obsolescent.
Logical operators:
and or is not in
There are also (1) the dot operator, (2) the subscript operator [], and the
function/method call operator ().
http://www.davekuhlman.org/python_101.html 10/81
11/17/2017 Python 101 --- Introduction to Python
For information on what the different operators do, the section in the "Python
Language Reference" titled "Special method names" may be of help:
http://docs.python.org/2/reference/datamodel.html#special-method-names
Operator Description
======================== ==================
lambda Lambda expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in Membership tests
is, is not Identity tests
<, <=, >, >=, <>, !=, == Comparisons
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Shifts
+, - Addition and subtraction
*, /, % Multiplication, division, remainder
+x, -x Positive, negative
~x Bitwise not
** Exponentiation
x.attribute Attribute reference
x[index] Subscription
x[index:index] Slicing
f(arguments...) Function call
(expressions...) Binding or tuple display
[expressions...] List display
{key:datum...} Dictionary display
`expressions...` String conversion
Note that most operators result in calls to methods with special names, for
example __add__, __sub__, __mul__, etc. See Special method names
http://docs.python.org/2/reference/datamodel.html#special-method-names
Later, we will see how these operators can be emulated in classes that you
define yourself, through the use of these special names.
Evaluating expressions.
Creating names/variables -- Binding -- The following all create names (variables) and
bind values (objects) to them: (1) assignment, (2) function definition, (3) class
definition, (4) function and method call, (5) importing a module, ...
First class objects -- Almost all objects in Python are first class. Definition: An object
is first class if: (1) we can put it in a structured object; (2) we can pass it to a
function; (3) we can return it from a function.
References -- Objects (or references to them) can be shared. What does this mean?
print obj
print "one", "two", 'three'
for: -- Example:
type(obj)
Learn what attributes an object has and what it's capabilities are -- Example:
dir(obj)
value = "a message"
http://www.davekuhlman.org/python_101.html 12/81
11/17/2017 Python 101 --- Introduction to Python
dir(value)
help(str)
help("")
value = "abc"
help(value)
help(value.upper)
In IPython (but not standard Python), you can also get help at the interactive prompt
by typing "?" and "??" after an object. Example:
In [48]: a = ''
In [49]: a.upper?
Type: builtin_function_or_method
String Form:<built-in method upper of str object at 0x7f1c426e0508>
Docstring:
S.upper() -> string
4 Built-in data-types
For information on built-in data types, see section Built-in Types --
http://docs.python.org/lib/types.html in the Python standard documentation.
Integer division truncates. This is changed in Python 3. Use float(n) to force coercion
to a float. Example:
In [8]: a = 4
In [9]: b = 5
In [10]: a / b
Out[10]: 0 # possibly wrong?
In [11]: float(a) / b
Out[11]: 0.8
http://www.davekuhlman.org/python_101.html 13/81
11/17/2017 Python 101 --- Introduction to Python
Scientific and heavily numeric programming -- High level Python is not very efficient
for numerical programming. But, there are libraries that help -- Numpy and SciPy --
See: SciPy: Scientific Tools for Python -- http://scipy.org/
range(n) creates a list of n integers. Optional arguments are the starting integer
and a stride.
xrange is like range, except that it creates an iterator that produces the items in
the list of integers instead of the list itself.
Python lists are (1) heterogeneous (2) indexable, and (3) dynamic. For example, we
can add to a list and make it longer.
To construct a tuple with a single element, use (x,); a tuple with a single
element requires a comma.
You can spread elements across multiple lines (and no need for backslash
continuation character "\").
A comma can follow the last element.
http://www.davekuhlman.org/python_101.html 14/81
11/17/2017 Python 101 --- Introduction to Python
Out[79]: True
In [80]: 44 in a
Out[80]: False
Subscription:
Operations on tuples -- No operations that change the tuple, since tuples are
immutable. We can do iteration and subscription. We can do "contains" (the in
operator) and get the length (the len() operator). We can use certain boolean
operators.
Append -- mylist.append(newitem).
Insert -- mylist.insert(index, newitem). Note on efficiency: The insert method is not
as fast as the append method. If you find that you need to do a large number of
mylist.insert(0, obj) (that is, inserting at the beginning of the list) consider using
a deque instead. See:
http://docs.python.org/2/library/collections.html#collections.deque. Or, use
append and reverse.
Extend -- mylist.extend(anotherlist). Also can use + and +=.
Remove -- mylist.remove(item) and mylist.pop(). Note that append() together with
pop() implements a stack.
Delete -- del mylist[index].
Pop -- Get last (right-most) item and remove from list -- mylist.pop().
Exercises:
Create an empty list. Append 4 strings to the list. Then pop one item off the
end of the list. Solution:
In [25]: a = []
In [26]: a.append('aaa')
In [27]: a.append('bbb')
In [28]: a.append('ccc')
In [29]: a.append('ddd')
In [30]: print a
['aaa', 'bbb', 'ccc', 'ddd']
In [31]: a.pop()
Out[31]: 'ddd'
Use the for statement to print the items in the list. Solution:
http://www.davekuhlman.org/python_101.html 15/81
11/17/2017 Python 101 --- Introduction to Python
Use the string join operation to concatenate the items in the list. Solution:
In [33]: '||'.join(a)
Out[33]: 'aaa||bbb||ccc'
Use lists containing three (3) elements to create and show a tree:
Note that we will learn a better way to represent tree structures when we cover
implementing classes in Python.
4.3 Strings
Strings are sequences. They are immutable. They are indexable. They are iterable.
>>> help(str)
Or:
>>> dir("abc")
Constructors/literals:
http://www.davekuhlman.org/python_101.html 16/81
11/17/2017 Python 101 --- Introduction to Python
Quotes: single and double. Escaping quotes and other special characters with a
back-slash.
Triple quoting -- Use triple single quotes or double quotes to define multi-line
strings.
str() -- The constructor and the name of the type/class.
'aSeparator'.join(aList)
Many more.
Examples:
If the right-hand argument to the formatting operator is a dictionary, then you can
(actually, must) use the names of keys in the dictionary in your format strings.
Examples:
Also consider using the right justify and left justify operations. Examples:
mystring.rjust(20), mystring.ljust(20, ':').
In Python 3, the str.format method is preferred to the string formatting operator. This
method is also available in Python 2.7. It has benefits and advantages over the string
formatting operator. You can start learning about it here:
http://docs.python.org/2/library/stdtypes.html#string-methods
Exercises:
Use a literal to create a string containing (1) a single quote, (2) a double quote,
(3) both a single and double quote. Solutions:
http://www.davekuhlman.org/python_101.html 17/81
11/17/2017 Python 101 --- Introduction to Python
"""This string
spans several lines
because it is a little long.
"""
Use the string join operation to create a string that contains a colon as a
separator. Solution:
>>> content = []
>>> content.append('finch')
>>> content.append('sparrow')
>>> content.append('thrush')
>>> content.append('jay')
>>> contentstr = ':'.join(content)
>>> print contentstr
finch:sparrow:thrush:jay
Use string formatting to produce a string containing your last and first names,
separated by a comma. Solution:
Incrementally building up large strings from lots of small strings -- the old way --
Since strings in Python are immutable, appending to a string requires a re-allocation.
So, it is faster to append to a list, then use join. Example:
In [25]: strlist = []
In [26]: strlist.append('Line #1')
In [27]: strlist.append('Line #2')
In [28]: strlist.append('Line #3')
In [29]: str = '\n'.join(strlist)
In [30]: print str
Line #1
Line #2
Line #3
Incrementally building up large strings from lots of small strings -- the new way --
The += operation on strings has been optimized. So, when you do this str1 += str2,
even many times, it is efficient.
The translate method enables us to map the characters in a string, replacing those in
one table by those in another. And, the maketrans function in the string module, makes
it easy to create the mapping table:
import string
http://www.davekuhlman.org/python_101.html 18/81
11/17/2017 Python 101 --- Introduction to Python
def test():
a = 'axbycz'
t = string.maketrans('abc', '123')
print a
print a.translate(t)
test()
http://docs.python.org/2/library/stdtypes.html#str.format
http://docs.python.org/2/library/string.html#format-string-syntax
http://docs.python.org/2/library/string.html#format-specification-mini-
language
Some examples:
In [96]: a = u'abcd'
In [97]: a
Out[97]: u'abcd'
In [98]: b = unicode('efgh')
In [99]: b
Out[99]: u'efgh'
In [102]: 'abcd'.decode('utf-8')
Out[102]: u'abcd'
In [103]:
In [104]: 'abcd'.decode(sys.getdefaultencoding())
Out[104]: u'abcd'
http://www.davekuhlman.org/python_101.html 19/81
11/17/2017 Python 101 --- Introduction to Python
In [107]: a = u'abcd'
In [108]: a.encode('utf-8')
Out[108]: 'abcd'
In [109]: a.encode(sys.getdefaultencoding())
Out[109]: 'abcd'
In [110]: b = u'Sel\xe7uk'
In [111]: print b.encode('utf-8')
Seluk
Or better:
You can also create a unicode character by using the unichr() built-in function:
Guidance for use of encodings and unicode -- If you are working with a multibyte
character set:
If you are reading and writing multibyte character data from or to a file, then look at
the codecs.open() in the codecs module --
http://docs.python.org/2/library/codecs.html#codecs.open.
Handling multi-byte character sets in Python 3 is easier, I think, but different. One
hint is to use the encoding keyword parameter to the open built-in function. Here is an
example:
def test():
infile = open('infile1.txt', 'r', encoding='utf-8')
outfile = open('outfile1.txt', 'w', encoding='utf-8')
for line in infile:
line = line.upper()
outfile.write(line)
infile.close()
outfile.close()
test()
4.4 Dictionaries
A dictionary is a collection, whose values are accessible by key. It is a collection of
name-value pairs.
The order of elements in a dictionary is undefined. But, we can iterate over (1) the
keys, (2) the values, and (3) the items (key-value pairs) in a dictionary. We can set
the value of a key and we can get the value associated with a key.
d1 = {}
d2 = {key1: value1, key2: value2, }
Constructor for dictionaries -- dict() can be used to create instances of the class dict.
Some examples:
http://www.davekuhlman.org/python_101.html 21/81
11/17/2017 Python 101 --- Introduction to Python
>>> help({})
Or:
>>> dir({})
In [102]: dict1 = {}
In [103]: dict1['name'] = 'dave'
In [104]: dict1['category'] = 38
In [105]: dict1
Out[105]: {'category': 38, 'name': 'dave'}
Some of the operations produce the keys, the values, and the items (pairs) in a
dictionary. Examples:
When iterating over large dictionaries, use methods iterkeys(), itervalues(), and
iteritems(). Example:
In [47]:
In [47]: d = {'aa': 111, 'bb': 222}
In [48]: for key in d.iterkeys():
....: print key
....:
....:
aa
bb
http://www.davekuhlman.org/python_101.html 22/81
11/17/2017 Python 101 --- Introduction to Python
To test for the existence of a key in a dictionary, use the in operator or the
mydict.has_key(k) method. The in operator is preferred. Example:
You can often avoid the need for a test by using method get. Example:
Dictionary "view" objects provide dynamic (automatically updated) views of the keys
or the values or the items in a dictionary. View objects also support set operations.
Create views with mydict.viewkeys(), mydict.viewvalues(), and mydict.viewitems(). See:
http://docs.python.org/2/library/stdtypes.html#dictionary-view-objects.
The dictionary setdefault method provides a way to get the value associated with a
key from a dictionary and to set that value if the key is missing. Example:
In [106]: a
Out[106]: {}
In [108]: a.setdefault('cc', 33)
Out[108]: 33
In [109]: a
Out[109]: {'cc': 33}
In [110]: a.setdefault('cc', 44)
Out[110]: 33
In [111]: a
Out[111]: {'cc': 33}
Exercises:
Write a literal that defines a dictionary using both string literals and variables
containing strings. Solution:
http://www.davekuhlman.org/python_101.html 23/81
11/17/2017 Python 101 --- Introduction to Python
Write statements that iterate over (1) the keys, (2) the values, and (3) the
items in a dictionary. (Note: Requires introduction of the for statement.)
Solutions:
You can use iterkeys(), itervalues(), iteritems() to obtain iterators over keys,
values, and items.
A dictionary itself is iterable: it iterates over its keys. So, the following two lines
are equivalent:
4.5 Files
http://www.davekuhlman.org/python_101.html 24/81
11/17/2017 Python 101 --- Introduction to Python
Notes:
Use the (built-in) open(path, mode) function to open a file and create a file object.
You could also use file(), but open() is recommended.
A file object that is open for reading a text file supports the iterator protocol
and, therefore, can be used in a for statement. It iterates over the lines in the
file. This is most likely only useful for text files.
open is a factory method that creates file objects. Use it to open files for reading,
writing, and appending. Examples:
infile.close()
outfile.close()
You can also use the with: statement to automatically close the file. Example:
The above works because a file is a context manager: it obeys the context
manager protocol. A file has methods __enter__ and __exit__, and the __exit__
method automatically closes the file for us. See the section on the with:
statement.
http://www.davekuhlman.org/python_101.html 25/81
11/17/2017 Python 101 --- Introduction to Python
In order to open multiple files, you can nest with: statements, or use a single
with: statement with multiple "expression as target" clauses. Example:
def test():
#
# use multiple nested with: statements.
with open('small_file.txt', 'r') as infile:
with open('tmp_outfile.txt', 'w') as outfile:
for line in infile:
outfile.write('line: %s' % line.upper())
print infile
print outfile
#
# use a single with: statement.
with open('small_file.txt', 'r') as infile, \
open('tmp_outfile.txt', 'w') as outfile:
for line in infile:
outfile.write('line: %s' % line.upper())
print infile
print outfile
test()
file is the file type and can be used as a constructor to create file objects. But,
open is preferred.
Lines read from a text file have a newline. Strip it off with something like:
line.rstrip('\n').
For binary files you should add the binary mode, for example: rb, wb. For more
about modes, see the description of the open() function at Built-in Functions --
http://docs.python.org/lib/built-in-funcs.html.
Learn more about file objects and the methods they provide at: 2.3.9 File
Objects -- http://docs.python.org/2/library/stdtypes.html#file-objects.
You can also append to an existing file. Note the "a" mode in the following example:
For binary files, add "b" to the mode. Not strictly necessary on UNIX, but needed on
MS Windows. And, you will want to make your code portable across platforms.
http://www.davekuhlman.org/python_101.html 26/81
11/17/2017 Python 101 --- Introduction to Python
Example:
Exercises:
Read all of the lines of a file into a list. Print the 3rd and 5th lines in the file/list.
Solution:
More notes:
Strip newlines (and other whitespace) from a string with methods strip(),
lstrip(), and rstrip().
Get the current position within a file by using myfile.tell().
Set the current position within a file by using myfile.seek(). It may be helpful to
use os.SEEK_CUR and os.SEEK_END. For example:
f.seek(2, os.SEEK_CUR) advances the position by two
f.seek(-3, os.SEEK_END) sets the position to the third to last.
http://www.davekuhlman.org/python_101.html 27/81
11/17/2017 Python 101 --- Introduction to Python
The following values also count as false, for example, in an if: statement: False,
numeric zero, None, the empty string, an empty list, an empty dictionary, any empty
container, etc. All other values, including True, act as true values.
Sets support several set operations, for example: union, intersection, difference, ...
>>> a = set()
>>> a
set([])
>>> a.add('aa')
>>> a.add('bb')
>>> a
http://www.davekuhlman.org/python_101.html 28/81
11/17/2017 Python 101 --- Introduction to Python
set(['aa', 'bb'])
>>> b = set([11, 22])
>>> b
set([11, 22])
>>> c = set([22, 33])
>>> b.union(c)
set([33, 11, 22])
>>> b.intersection(c)
set([22])
An overview of the structure of a typical class: (1) methods; (2) the constructor; (3)
class (static) variables; (4) super/subclasses.
6 Statements
Possible targets:
Identifier
Tuple or list -- Can be nested. Left and right sides must have equivalent
structure. Example:
http://www.davekuhlman.org/python_101.html 29/81
11/17/2017 Python 101 --- Introduction to Python
In [10]: a = range(10)
In [11]: a
Out[11]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [12]: a[3] = 'abc'
In [13]: a
Out[13]: [0, 1, 2, 'abc', 4, 5, 6, 7, 8, 9]
In [14]:
In [14]: b = {'aa': 11, 'bb': 22}
In [15]: b
Out[15]: {'aa': 11, 'bb': 22}
In [16]: b['bb'] = 1000
In [17]: b['cc'] = 2000
In [18]: b
Out[18]: {'aa': 11, 'bb': 1000, 'cc': 2000}
In [1]: a = range(10)
In [2]: a
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]: a[2:5] = [11, 22, 33, 44, 55, 66]
In [4]: a
Out[4]: [0, 1, 11, 22, 33, 44, 55, 66, 5, 6, 7, 8, 9]
>>> index = 0
>>> index += 1
>>> index += 5
>>> index += f(x)
>>> index -= 1
>>> index *= 3
http://www.davekuhlman.org/python_101.html 30/81
11/17/2017 Python 101 --- Introduction to Python
Things to note:
Assignment to a name creates a new variable (if it does not exist in the
namespace) and a binding. Specifically, it binds a value to the new name.
Calling a function also does this to the (formal) parameters within the local
namespace.
In Python, a language with dynamic typing, the data type is associated with the
value, not the variable, as is the case in statically typed languages.
obj1 = A()
obj2 = obj1
Check to determine that the same object is shared with id(obj) or the is
operator. Example:
In [23]: a = range(10)
In [24]: a
Out[24]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [25]: b = a
In [26]: b
Out[26]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [27]: b[3] = 333
In [28]: b
Out[28]: [0, 1, 2, 333, 4, 5, 6, 7, 8, 9]
In [29]: a
Out[29]: [0, 1, 2, 333, 4, 5, 6, 7, 8, 9]
In [30]: a is b
Out[30]: True
In [31]: print id(a), id(b)
31037920 31037920
In [32]: a = b = 123
In [33]: a
Out[33]: 123
In [34]: b
Out[34]: 123
In [35]:
In [35]:
In [35]: a = b = [11, 22]
In [36]: a is b
Out[36]: True
You can interchange (swap) the value of two variables using assignment and
packing/unpacking:
>>> a = 111
>>> b = 222
http://www.davekuhlman.org/python_101.html 31/81
11/17/2017 Python 101 --- Introduction to Python
>>> a, b = b, a
>>> a
222
>>> b
111
Evaluation of a specific module only happens once during a given run of the
program. Therefore, a module is shared across an application.
A module is evaluated from top to bottom. Later statements can replace values
created earlier. This is true of functions and classes, as well as (other)
variables.
Use the following idiom to make a module both run-able and import-able:
if __name__ == '__main__':
# import pdb; pdb.set_trace()
main() # or "test()" or some other function defined in modul
Notes:
The above condition will be true only when the module is run as a script
and will not be true when the module is imported.
The line containing pdb can be copied any place in your program and un-
commented, and then the program will drop into the Python debugger
when that location is reached.
import sys
sys.path.insert(0, '/path/to/my/module')
http://www.davekuhlman.org/python_101.html 32/81
11/17/2017 Python 101 --- Introduction to Python
import A -- Names in the local (module) namespace are accessible with the dot
operator.
import A as B -- Import the module A, but bind the module object to the variable
B.
import A1, A2 -- Not recommended
from A import B
from A import B1, B2
from A import B as C
from A import * -- Not recommended: clutters and mixes name-spaces.
from A.B import C -- (1) Possibly import object C from module B in package A or (2)
possibly import module C from sub-package B in package A.
import A.B.C -- To reference attributes in C, must use fully-qualified name, for
example use A.B.C.D to reference D inside of C.
Using dots in the import statement -- From the Python language reference
manual:
Exercises:
http://www.davekuhlman.org/python_101.html 33/81
11/17/2017 Python 101 --- Introduction to Python
Import an element from a module from the standard library, for example import
compile from the re module.
Arguments to print:
Can also use sys.stdout. Note that a carriage return is not automatically added.
Example:
Controlling the destination and format of print -- Replace sys.stdout with an instance
of any class that implements the method write taking one parameter. Example:
import sys
class Writer:
def __init__(self, file_name):
http://www.davekuhlman.org/python_101.html 34/81
11/17/2017 Python 101 --- Introduction to Python
def test():
writer = Writer('outputfile.txt')
save_stdout = sys.stdout
sys.stdout = writer
print 'hello'
print 'goodbye'
writer.close()
# Show the output.
tmp_file = file('outputfile.txt')
sys.stdout = save_stdout
content = tmp_file.read()
tmp_file.close()
print content
test()
There is an alternative form of the print statement that takes a file-like object, in
particular an object that has a write method. For example:
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
http://www.davekuhlman.org/python_101.html 35/81
11/17/2017 Python 101 --- Introduction to Python
else:
statements
Conditions -- Expressions -- Anything that returns a value. Compare with eval() and
exec.
Truth values:
False -- False, None, numeric zero, the empty string, an empty collection (list or
tuple or dictionary or ...).
True -- True and everything else.
Operators:
and and or -- Note that both and and or do short circuit evaluation.
not
is and is not -- The identical object. Cf. a is b and id(a) == id(b). Useful to test
for None, for example:
if x is None:
...
if x is not None:
...
in and not in -- Can be used to test for existence of a key in a dictionary or for
the presence of a value in a collection.
Example:
>>> a = 'aa'
>>> b = 'bb'
>>> x = 'yes' if a == b else 'no'
>>> x
'no'
http://www.davekuhlman.org/python_101.html 36/81
11/17/2017 Python 101 --- Introduction to Python
Notes:
Exercises:
Form:
for x in y:
block
http://www.davekuhlman.org/python_101.html 37/81
11/17/2017 Python 101 --- Introduction to Python
class A(object):
def __init__(self):
self.data = [11,22,33]
self.idx = 0
def __iter__(self):
return self
def next(self):
if self.idx < len(self.data):
x = self.data[self.idx]
self.idx +=1
return x
else:
raise StopIteration
def test():
a = A()
for x in a:
print x
test()
Yield expressions --
http://docs.python.org/2/reference/expressions.html#yield-expressions
The yield statement --
http://docs.python.org/2/reference/simple_stmts.html#the-yield-
statement
Also see itertools module in the Python standard library for much more help
with iterators: itertools Functions creating iterators for efficient looping --
http://docs.python.org/2/library/itertools.html#module-itertools
http://www.davekuhlman.org/python_101.html 38/81
11/17/2017 Python 101 --- Introduction to Python
2. cherry
3. date
The for statement can also have an optional else: clause. The else: clause is executed
if the for statement completes normally, that is if a break statement is not executed.
List comprehensions -- Since list comprehensions create lists, they are useful in for
statements, although, when the number of elements is large, you should consider
using a generator expression instead. A list comprehension looks a bit like a for:
statement, but is inside square brackets, and it is an expression, not a statement.
Two forms (among others):
Exercises:
Write a list comprehension that returns all the keys in a dictionary whose
associated values are greater than zero.
The dictionary: {'aa': 11, 'cc': 33, 'dd': -55, 'bb': 22}
Solution: [x[0] for x in my_dict.iteritems() if x[1] > 0]
http://www.davekuhlman.org/python_101.html 39/81
11/17/2017 Python 101 --- Introduction to Python
Write a list comprehension that produces even integers from 0 to 10. Use a for
statement to iterate over those values. Solution:
Write a list comprehension that iterates over two lists and produces all the
combinations of items from the lists. Solution:
In [19]: a = range(4)
In [20]: b = [11,22,33]
In [21]: a
Out[21]: [0, 1, 2, 3]
In [22]: b
Out[22]: [11, 22, 33]
In [23]: c = [(x, y) for x in a for y in b]
In [24]: print c
[(0, 11), (0, 22), (0, 33), (1, 11), (1, 22), (1, 33),
(2, 11), (2, 22), (2, 33), (3, 11), (3, 22), (3, 33)]
But, note that in the previous exercise, a generator expression would often be better.
A generator expression is like a list comprehension, except that, instead of creating
the entire list, it produces a generator that can be used to produce each of the
elements.
The break and continue statements are often useful in a for statement. See continue
and break statements
The for statement can also have an optional else: clause. The else: clause is executed
if the for statement completes normally, that is if a break statement is not executed.
Example:
while condition:
block
http://www.davekuhlman.org/python_101.html 40/81
11/17/2017 Python 101 --- Introduction to Python
The while: statement is not often used in Python because the for: statement is usually
more convenient, more idiomatic, and more Pythonic.
Exercises:
count = 0
while count < 5:
count += 1
print count
The break and continue statements are often useful in a while statement. See continue
and break statements
The while statement can also have an optional else: clause. The else: clause is
executed if the while statement completes normally, that is if a break statement is not
executed.
The continue statement causes execution to immediately continue at the start of the
loop.
When the for: statement or the while: statement has an else: clause, the block in the
else: clause is executed only if a break statement is not executed.
Exercises:
Using break, write a while statement that prints integers from zero to 5. Solution:
count = 0
while True:
count += 1
if count > 5:
break
print count
Notes:
A for statement that uses range() or xrange() would be better than a while
statement for this use.
Using continue, write a while statement that processes only even integers from 0
to 10. Note: % is the modulo operator. Solution:
http://www.davekuhlman.org/python_101.html 41/81
11/17/2017 Python 101 --- Introduction to Python
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue
print count
Evaluation (execution model) of the try statement -- When an exception occurs in the
try block, even if inside a nested function call, execution of the try block ends and the
except clauses are searched for a matching exception.
An exception class in an except: clause catches instances of that exception class and
all subclasses, but not superclasses.
Module exceptions.
Built-in exceptions -- http://docs.python.org/lib/module-exceptions.html.
Example:
try:
raise RuntimeError('this silly error')
except RuntimeError, exp:
print "[[[%s]]]" % exp
Reference: http://docs.python.org/lib/module-exceptions.html
You can also get the arguments passed to the constructor of an exception object. In
the above example, these would be:
http://www.davekuhlman.org/python_101.html 42/81
11/17/2017 Python 101 --- Introduction to Python
exp.args
Why would you define your own exception class? One answer: You want a user of
your code to catch your exception and no others.
Catching an exception by exception class catches exceptions of that class and all its
subclasses. So:
So:
class MyE(ValueError):
pass
try:
raise MyE()
except ValueError:
print 'caught exception'
Also see the entries for "EAFP" and "LBYL" in the Python glossary:
http://docs.python.org/3/glossary.html.
Exercises:
class MyE(Exception):
pass
Write a try:except: statement that raises your exception and also catches it.
Solution:
try:
raise MyE('hello there dave')
except MyE, e:
print e
Forms:
raise instance
raise MyExceptionClass(value) -- preferred.
raise MyExceptionClass, value
See http://docs.python.org/ref/raise.html.
The following example defines an exception subclass and throws an instance of that
subclass. It also shows how to pass and catch multiple arguments to the exception:
class NotsobadError(Exception):
pass
def test(x):
try:
if x == 0:
raise NotsobadError('a moderately bad error', 'not too bad')
except NotsobadError, e:
print 'Error args: %s' % (e.args, )
test(0)
Notes:
class NotsobadError(Exception):
"""An exception class.
"""
def get_args(self):
return '::::'.join(self.args)
http://www.davekuhlman.org/python_101.html 44/81
11/17/2017 Python 101 --- Introduction to Python
def test(x):
try:
if x == 0:
raise NotsobadError('a moderately bad error', 'not too bad')
except NotsobadError, e:
print 'Error args: {{{%s}}}' % (e.get_args(), )
test(0)
class Context01(object):
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
pass
class Context01(object):
def __enter__(self):
print 'in __enter__'
return 'some value or other' # usually we want to return self
def __exit__(self, exc_type, exc_value, traceback):
print 'in __exit__'
Notes:
Usually, but not always, we will want the __enter__ method to return self, that is,
the instance of our context manager class. We do this so that we can write:
and then use the instance (obj in this case) in the nested block.
The __exit__ method is called when our block of code is exited either normally or
because of an exception.
http://www.davekuhlman.org/python_101.html 45/81
11/17/2017 Python 101 --- Introduction to Python
Otherwise, the exception will be processed normally upon exit from this
method.
If the block exits normally, the value of exc_type, exc_value, and traceback will be
None.
For more information on the with: statement, see Context Manager Types --
http://docs.python.org/2/library/stdtypes.html#context-manager-types.
# example 1
with Context01():
print 'in body'
# example 2
with Context02() as a_value:
print 'in body'
print 'a_value: "%s"' % (a_value, )
a_value.some_method_in_Context02()
# example 3
with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile:
for line in infile:
line = line.rstrip()
outfile.write('%s\n' % line.upper())
Notes:
In the form with ... as val, the value returned by the __enter__ method is
assigned to the variable (val in this case).
In order to use more than one context manager, you can nest with: statements,
or separate uses of of the context managers with commas, which is usually
preferred. See example 3 above.
6.11 del
The del statement can be used to:
If name is listed in a global statement, then del removes name from the global
namespace.
http://www.davekuhlman.org/python_101.html 46/81
11/17/2017 Python 101 --- Introduction to Python
>>> del a
>>> del a, b, c
We can also delete items from a list or dictionary (and perhaps from other objects
that we can subscript). Examples:
In [17]:class A:
....: pass
....:
In [18]:a = A()
In [19]:a.x = 123
In [20]:dir(a)
Out[20]:['__doc__', '__module__', 'x']
In [21]:print a.x
123
In [22]:del a.x
In [23]:dir(a)
Out[23]:['__doc__', '__module__']
In [24]:print a.x
----------------------------------------------
exceptions.AttributeError Traceback (most recent call last)
/home/dkuhlman/a1/Python/Test/<console>
7.1 Functions
http://www.davekuhlman.org/python_101.html 47/81
11/17/2017 Python 101 --- Introduction to Python
Although the def statement is evaluated, the code in its nested block is not executed.
Therefore, many errors may not be detected until each and every path through that
code is tested. Recommendations: (1) Use a Python code checker, for example flake8
or pylint; (2) Do thorough testing and use the Python unittest framework. Pythonic
wisdom: If it's not tested, it's broken.
The return statement takes zero or more values, separated by commas. Using
commas actually returns a single tuple.
To return multiple values, use a tuple or list. Don't forget that (assignment)
unpacking can be used to capture multiple values. Returning multiple items
separated by commas is equivalent to returning a tuple. Example:
7.1.3 Parameters
Default values -- Example:
2
3
4
Note: If a function has a parameter with a default value, then all "normal" arguments
must proceed the parameters with default values. More completely, parameters must
be given from left to right in the following order:
1. Normal arguments.
2. Arguments with default values.
3. Argument list (*args).
4. Keyword arguments (**kwargs).
7.1.4 Arguments
When calling a function, values may be passed to a function with positional
arguments or keyword arguments.
Positional arguments must placed before (to the left of) keyword arguments.
Variable look-up -- The LGB/LEGB rule -- The local, enclosing, global, built-in scopes
are searched in that order. See: http://www.python.org/dev/peps/pep-0227/
The global statement -- Inside a function, we must use global when we want to set the
value of a global variable. Example:
def fn():
global Some_global_variable, Another_global_variable
Some_global_variable = 'hello'
...
http://www.davekuhlman.org/python_101.html 49/81
11/17/2017 Python 101 --- Introduction to Python
Functions are first-class -- You can store them in a structure, pass them to a
function, and return them from a function.
>>> test(size=25)
You can "capture" remaining arguments with *args, and **kwargs. (Spelling is not
significant.) Example:
Normal arguments must come before default arguments which must come
before keyword arguments.
In order to set the value of a global variable, declare the variable with global.
Exercises:
Write a function that takes a single argument, prints the value of the argument,
and returns the argument as a string. Solution:
Write a function that takes a variable number of arguments and prints them all.
Solution:
http://www.davekuhlman.org/python_101.html 50/81
11/17/2017 Python 101 --- Introduction to Python
Write a function that prints the names and values of keyword arguments passed
to it. Solution:
In order to assign a value to a global variable, declare the variable as global at the
beginning of the function or method.
If in a function or method, you both reference and assign to a variable, then you
must either:
Some examples:
In [1]:
In [1]: X = 3
In [2]: def t():
...: print X
...:
In [3]:
In [3]: t()
3
In [4]: def s():
...: X = 4
...:
http://www.davekuhlman.org/python_101.html 51/81
11/17/2017 Python 101 --- Introduction to Python
In [5]:
In [5]:
In [5]: s()
In [6]: t()
3
In [7]: X = -1
In [8]: def u():
...: global X
...: X = 5
...:
In [9]:
In [9]: u()
In [10]: t()
5
In [16]: def v():
....: x = X
....: X = 6
....: return x
....:
In [17]:
In [17]: v()
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
File "<ipython console>", line 2, in v
UnboundLocalError: local variable 'X' referenced before assignment
In [18]: def w():
....: global X
....: x = X
....: X = 7
....: return x
....:
In [19]:
In [19]: w()
Out[19]: 5
In [20]: X
Out[20]: 7
A decorator is applied using the "@" character on a line immediately preceeding the
function definition header. Examples:
class SomeClass(object):
http://www.davekuhlman.org/python_101.html 52/81
11/17/2017 Python 101 --- Introduction to Python
@classmethod
def HelloClass(cls, arg):
pass
## HelloClass = classmethod(HelloClass)
@staticmethod
def HelloStatic(arg):
pass
## HelloStatic = staticmethod(HelloStatic)
#
# Define/implement a decorator.
def wrapper(fn):
def inner_fn(*args, **kwargs):
print '>>'
result = fn(*args, **kwargs)
print '<<'
return result
return inner_fn
#
# Apply a decorator.
@wrapper
def fn1(msg):
pass
## fn1 = wrapper(fn1)
Notes:
The decorator form (with the "@" character) is equivalent to the form
(commented out) that calls the decorator function explicitly.
The use of classmethods and staticmethod will be explained later in the section on
object-oriented programming.
A decorator is implemented as a function. Therefore, to learn about some
specific decorator, you should search for the documentation on or the
implementation of that function. Remember that in order to use a function, it
must be defined in the current module or imported by the current module or be
a built-in.
The form that explicitly calls the decorator function (commented out in the
example above) is equivalent to the form using the "@" character.
7.2 lambda
Use a lambda, as a convenience, when you need a function that both:
Example:
In [1]: fn = lambda x, y, z: (x ** 2) + (y * 2) + z
In [2]: fn(4, 5, 6)
Out[2]: 32
In [3]:
In [3]: format = lambda obj, category: 'The "%s" is a "%s".' % (obj, categor
In [4]: format('pine tree', 'conifer')
O t[4] 'Th " i t " i " if " '
http://www.davekuhlman.org/python_101.html 53/81
11/17/2017 Python 101 --- Introduction to Python
Out[4]: 'The "pine tree" is a "conifer".'
A lambda can take multiple arguments and can return (like a function) multiple
values. Example:
Example:
class Test:
def __init__(self, first='', last=''):
self.first = first
self.last = last
def test(self, formatter):
"""
Test for lambdas.
formatter is a function taking 2 arguments, first and last
names. It should return the formatted name.
"""
msg = 'My name is %s' % (formatter(self.first, self.last),)
print msg
def test():
t = Test('Dave', 'Kuhlman')
t.test(lambda first, last: '%s %s' % (first, last, ))
t.test(lambda first, last: '%s, %s' % (last, first, ))
test()
A lambda enables us to define "functions" where we do not need names for those
functions. Example:
In [45]: a = [
....: lambda x: x,
....: lambda x: x * 2,
....: ]
In [46]:
In [46]: a
Out[46]: [<function __main__.<lambda>>, <function __main__.<lambda>>]
In [47]: a[0](3)
Out[47]: 3
In [48]: a[1](3)
Out[48]: 6
Reference: http://docs.python.org/2/reference/expressions.html#lambda
Concepts:
iterator
And iterator is something that satisfies the iterator protocol. Clue: If it's an
iterator, you can use it in a for: statement.
generator
A generator is a class or function that implements an iterator, i.e. that
implements the iterator protocol.
yield
The yield statement enables us to write functions that are generators. Such
functions may be similar to coroutines, since they may "yield" multiple times
and are resumed.
For more information on iterators, see the section on iterator types in the Python
Library Reference -- http://docs.python.org/2/library/stdtypes.html#iterator-types.
Actually, yield is an expression. For more on yield expressions and on the next() and
send() generator methods, as well as others, see: Yield expression --
http://docs.python.org/2/reference/expressions.html#yield-expressions in the
Python language reference manual.
def simplegenerator():
yield 'aaa' # Note 1
http://www.davekuhlman.org/python_101.html 55/81
11/17/2017 Python 101 --- Introduction to Python
yield 'bbb'
yield 'ccc'
def list_tripler(somelist):
for item in somelist:
item *= 3
yield item
def test():
print '1.', '-' * 30
it = simplegenerator()
for item in it:
print item
print '2.', '-' * 30
alist = range(5)
it = list_tripler(alist)
for item in it:
print item
print '3.', '-' * 30
alist = range(8)
it = limit_iterator(alist, 4)
for item in it:
print item
print '4.', '-' * 30
it = simplegenerator()
try:
print it.next() # Note 3
print it.next()
print it.next()
print it.next()
except StopIteration, exp: # Note 4
print 'reached end of sequence'
if __name__ == '__main__':
test()
Notes:
1. The yield statement returns a value. When the next item is requested and the
iterator is "resumed", execution continues immediately after the yield
statement.
2. We can terminate the sequence generated by an iterator by using a return
statement with no value.
3. To resume a generator, use the generator's next() or send() methods. send() is
like next(), but provides a value to the yield expression.
4. We can alternatively obtain the items in a sequence by calling the iterator's
next() method. Since an iterator is a first-class object, we can save it in a data
structure and can pass it around for use at different locations and times in our
program.
http://www.davekuhlman.org/python_101.html 56/81
11/17/2017 Python 101 --- Introduction to Python
$ python test_iterator.py
1. ------------------------------
aaa
bbb
ccc
2. ------------------------------
0
3
6
9
12
3. ------------------------------
0
1
2
3
4
4. ------------------------------
aaa
bbb
ccc
reached end of sequence
Examples -- The following code implements an iterator that produces all the objects
in a tree of objects:
class Node:
def __init__(self, data, children=None):
self.initlevel = 0
self.data = data
if children is None:
self.children = []
else:
self.children = children
def set_initlevel(self, initlevel): self.initlevel = initlevel
def get_initlevel(self): return self.initlevel
def addchild(self, child):
self.children.append(child)
def get_data(self):
return self.data
def get_children(self):
return self.children
def show_tree(self, level):
http://www.davekuhlman.org/python_101.html 57/81
11/17/2017 Python 101 --- Introduction to Python
self.show_level(level)
print 'data: %s' % (self.data, )
for child in self.children:
child.show_tree(level + 1)
def show_level(self, level):
print ' ' * level,
#
# Generator method #1
# This generator turns instances of this class into iterable objects.
#
def walk_tree(self, level):
yield (level, self, )
for child in self.get_children():
for level1, tree1 in child.walk_tree(level+1):
yield level1, tree1
def __iter__(self):
return self.walk_tree(self.initlevel)
#
# Generator method #2
# This generator uses a support function (walk_list) which calls
# this function to recursively walk the tree.
# If effect, this iterates over the support function, which
# iterates over this function.
#
def walk_tree(tree, level):
yield (level, tree)
for child in walk_list(tree.get_children(), level+1):
yield child
#
# Generator method #3
# This generator is like method #2, but calls itself (as an iterator),
# rather than calling a support function.
#
def walk_tree_recur(tree, level):
yield (level, tree,)
for child in tree.get_children():
for level1, tree1 in walk_tree_recur(child, level+1):
yield (level1, tree1, )
def show_level(level):
print ' ' * level,
def test():
a7 = Node('777')
a6 = Node('666')
a5 = Node('555')
http://www.davekuhlman.org/python_101.html 58/81
11/17/2017 Python 101 --- Introduction to Python
a4 = Node('444')
a3 = Node('333', [a4, a5])
a2 = Node('222', [a6, a7])
a1 = Node('111', [a2, a3])
initLevel = 2
a1.show_tree(initLevel)
print '=' * 40
for level, item in walk_tree(a1, initLevel):
show_level(level)
print 'item:', item.get_data()
print '=' * 40
for level, item in walk_tree_recur(a1, initLevel):
show_level(level)
print 'item:', item.get_data()
print '=' * 40
a1.set_initlevel(initLevel)
for level, item in a1:
show_level(level)
print 'item:', item.get_data()
iter1 = iter(a1)
print iter1
print iter1.next()
print iter1.next()
print iter1.next()
print iter1.next()
print iter1.next()
print iter1.next()
print iter1.next()
## print iter1.next()
return a1
if __name__ == '__main__':
test()
Notes:
7.4 Modules
A module is a Python source code file.
A module can be imported. When imported, the module is evaluated, and a module
object is created. The module object has attributes. The following attributes are of
special interest:
-- The name of the module when the module is imported, but the string
__name__
"__main__" when the module is executed.
Other names that are created (bound) in the module.
To make a module both import-able and run-able, use the following idiom (at the end
of the module):
def main():
o
o
o
if __name__ == '__main__':
main()
See sys.path.
Standard places.
Environment variable PYTHONPATH.
A module is an object.
A module (object) can be shared.
A specific module is imported only once in a single run. This means that a single
module object is shared by all the modules that import it.
7.5 Packages
A package is a directory on the file system which contains a file named __init__.py.
What can you do with it? -- Any code that should be executed exactly once and
during import. For example:
Then, from my_package import * will import func1 and func2, but not other names
defined in my_package.
Note that __all__ can be used at the module level, as well as at the package
level.
For more information, see the section on packages in the Python tutorial:
http://docs.python.org/2/tutorial/modules.html#packages.
"Flat is better" -- Use the __init__.py file to present a "flat" view of the API for
your code. Enable your users to do import mypackage and then reference:
mypackage.item1
mypackage.item2
mypackage.item3
Etc.
Where item1, item2, etc compose the API you want your users to use, even
though the implementation of these items may be buried deep in your code.
Use the __init__.py module to present a "clean" API. Present only the items that
you intend your users to use, and by doing so, "hide" items you do not intend
them to use.
8 Classes
Classes model the behavior of objects in the "real" world. Methods implement the
behaviors of these types of objects. Member variables hold (current) state. Classes
enable us to implement new data types in Python.
The class: statement is used to define a class. The class: statement creates a class
object and binds it to a name.
http://www.davekuhlman.org/python_101.html 61/81
11/17/2017 Python 101 --- Introduction to Python
To define a new style class (recommended), inherit from object or from another class
that does. Example:
Exercise: Define a class with a member variable name and a show method. Use print to
show the name. Solution:
Notes:
The self variable is explicit. It references the current object, that is the object
whose method is currently executing.
The spelling ("self") is optional, but everyone spells it that way.
http://www.davekuhlman.org/python_101.html 62/81
11/17/2017 Python 101 --- Introduction to Python
class A(object):
def __init__(self, name):
self.name = name
Do not do this:
In [29]: class B:
....: def __init__(self, items=[]): # wrong. list ctor evaluated o
....: self.items = items
In the second example, the def statement and the list constructor are evaluated only
once. Therefore, the item member variable of all instances of class B, will share the
same value, which is most likely not what you want.
some_object.some_method()
an_array_of_of_objects[1].another_method()
self.a_method()
From with a subclass when the method is in the superclass and there is a
method with the same name in the current class -- Use the class (name)
or use super:
http://www.davekuhlman.org/python_101.html 63/81
11/17/2017 Python 101 --- Introduction to Python
The use of super() may solve problems searching for the base class when using
multiple inheritance. A better solution is to not use multiple inheritance.
You can also use multiple inheritance. But, it can cause confusion. For example, in
the following, class C inherits from both A and B:
For more information on inheritance, see the tutorial in the standard Python
documentation set: 9.5 Inheritance and 9.5.1 Multiple Inheritance.
Watch out for problems with inheriting from multiple classes that have a common
base class.
class A(object):
size = 5
def get_size(self):
return A.size
http://www.davekuhlman.org/python_101.html 64/81
11/17/2017 Python 101 --- Introduction to Python
Class methods:
Static methods:
A static method receives neither the instance nor the class as its first argument.
Define static methods with built-in function staticmethod() or with decorator
@staticmethod.
See the description of staticmethod() built-in function at "Built-in Functions":
http://docs.python.org/2/library/functions.html#staticmethod
Notes on decorators:
@afunc
def m(self): pass
You can use decorators @classmethod and @staticmethod (instead of the classmethod()
and staticmethod() built-in functions) to declare class methods and static
methods.
Example:
class B(object):
Count = 0
def dup_string(x):
s1 = '%s%s' % (x, x,)
return s1
dup_string = staticmethod(dup_string)
@classmethod
def show_count(cls, msg):
print '%s %d' % (msg, cls.Count, )
http://www.davekuhlman.org/python_101.html 65/81
11/17/2017 Python 101 --- Introduction to Python
def test():
print B.dup_string('abcd')
B.show_count('here is the count: ')
8.9 Properties
The property built-in function enables us to write classes in a way that does not
require a user of the class to use getters and setters. Example:
class TestProperty(object):
def __init__(self, description):
self._description = description
def _set_description(self, description):
print 'setting description'
self._description = description
def _get_description(self):
print 'getting description'
return self._description
description = property(_get_description, _set_description)
The property built-in function is also a decorator. So, the following is equivalent to the
above example:
http://www.davekuhlman.org/python_101.html 66/81
11/17/2017 Python 101 --- Introduction to Python
class TestProperty(object):
def __init__(self, description):
self._description = description
@property
def description(self):
print 'getting description'
return self._description
@description.setter
def description(self, description):
print 'setting description'
self._description = description
Notes:
8.10 Interfaces
In Python, to implement an interface is to implement a method with a specific name
and a specific arguments.
"Duck typing" -- If it walks like a duck and quacks like a duck ...
One way to define an "interface" is to define a class containing methods that have a
header and a doc string but no implementation.
class C(list):
def get_len(self):
return len(self)
c = C((11,22,33))
c.get_len()
http://www.davekuhlman.org/python_101.html 67/81
11/17/2017 Python 101 --- Introduction to Python
c = C((11,22,33,44,55,66,77,88))
print c.get_len()
# Prints "8".
A slightly more complex example -- the following class extends the dictionary
data-type:
class D(dict):
def __init__(self, data=None, name='no_name'):
if data is None:
data = {}
dict.__init__(self, data)
self.name = name
def get_len(self):
return len(self)
def get_keys(self):
content = []
for key in self:
content.append(key)
contentstr = ', '.join(content)
return contentstr
def get_name(self):
return self.name
def test():
d = D({'aa': 111, 'bb':222, 'cc':333})
# Prints "3"
print d.get_len()
# Prints "'aa, cc, bb'"
print d.get_keys()
# Prints "no_name"
print d.get_name()
Exercises:
http://www.davekuhlman.org/python_101.html 68/81
11/17/2017 Python 101 --- Introduction to Python
Give the superclass one member variable, a name, which can be entered
when an instance is constructed.
Give the subclass one member variable, a description; the subclass
constructor should allow entry of both name and description.
Put a show() method in the superclass and override the show() method in the
subclass.
Solution:
class A(object):
def __init__(self, name):
self.name = name
def show(self):
print 'name: %s' % (self.name, )
class B(A):
def __init__(self, name, desc):
A.__init__(self, name)
self.desc = desc
def show(self):
A.show(self)
print 'desc: %s' % (self.desc, )
9 Special Tasks
pdb.run('expression')
Example:
if __name__ == '__main__':
import pdb
pdb.run('main()')
http://www.davekuhlman.org/python_101.html 69/81
11/17/2017 Python 101 --- Introduction to Python
Example:
if __name__ == '__main__':
import pdb
pdb.set_trace()
main()
(Pdb) help
(Pdb) help next
ipdb -- Also consider using ipdb (and IPython). The ipdb debugger interactive prompt has
some additional features, for example, it does tab name completion.
Inspecting:
import inspect
See http://docs.python.org/lib/module-inspect.html.
Don't forget to try dir(obj) and type(obj) and help(obj), first.
Miscellaneous tools:
id(obj)
globals() and locals().
dir(obj) -- Returns interesting names, but list is not necessarily complete.
obj.__class__
cls.__bases__
obj.__class__.__bases__
obj.__doc__. But usually, help(obj) is better.It produces the doc string.
Customize the representation of your class. Define the following methods in
your class:
__repr__() -- Called by (1) repr(), (2) interactive interpreter when
representation is needed.
__str__() -- Called by (1) str(), (2) string formatting.
pdb is implemented with the cmd module in the Python standard library. You can
implement similar command line interfaces by using cmd. See: cmd -- Support for
line-oriented command interpreters -- http://docs.python.org/lib/module-cmd.html.
http://www.davekuhlman.org/python_101.html 70/81
11/17/2017 Python 101 --- Introduction to Python
def test():
f = file('tmp.py', 'r')
for line in f:
print 'line:', line.rstrip()
f.close()
test()
Notes:
A text file is an iterable. It iterates over the lines in a file. The following is a
common idiom:
string.rstrip() strips new-line and other whitespace from the right side of each
line. To strip new-lines only, but not other whitespace, try rstrip('\n').
def test():
f = file('tmp.txt', 'w')
for ch in 'abcdefg':
f.write(ch * 10)
f.write('\n')
f.close()
test()
Notes:
The write method, unlike the print statement, does not automatically add new-
line characters.
Must close file in order to flush output. Or, use my_file.flush().
And, don't forget the with: statement. It makes closing files automatic. The following
example converts all the vowels in an input file to upper case and writes the
converted lines to an output file:
import string
http://www.davekuhlman.org/python_101.html () 71/81
11/17/2017 Python 101 --- Introduction to Python
line = line.rstrip()
outfile.write('%s\n' % line.translate(tran_table))
For help and more information do the following at the Python interactive prompt:
And, you can read the source: Lib/unittest.py in the Python standard library.
import unittest
class UnitTests02(unittest.TestCase):
def testFoo(self):
self.failUnless(False)
class UnitTests01(unittest.TestCase):
def testBar01(self):
self.failUnless(False)
def testBar02(self):
self.failUnless(False)
def main():
unittest.main()
if __name__ == '__main__':
main()
Notes:
The call to unittest.main() runs all tests in all test fixtures in the module. It
actually creates an instance of class TestProgram in module Lib/unittest.py, which
automatically runs tests.
http://www.davekuhlman.org/python_101.html 72/81
11/17/2017 Python 101 --- Introduction to Python
Within a test fixture (a class), the tests are any methods whose names begin
with the prefix "test".
In any test, we check for success or failure with inherited methods such as
failIf(), failUnless(), assertNotEqual(), etc. For more on these methods, see the
library documentation for the unittest module TestCase Objects --
http://docs.python.org/lib/testcase-objects.html.
If you want to change (1) the test method prefix or (2) the function used to sort
(the order of) execution of tests within a test fixture, then you can create your
own instance of class unittest.TestLoader and customize it. For example:
def main():
my_test_loader = unittest.TestLoader()
my_test_loader.testMethodPrefix = 'check'
my_test_loader.sortTestMethodsUsing = my_cmp_func
unittest.main(testLoader=my_test_loader)
if __name__ == '__main__':
main()
But, see the notes in section Additional unittest features for instructions on a
(possibly) better way to do this.
#!/usr/bin/env python
class GenTest(unittest.TestCase):
def test_1_generate(self):
cmd = 'python ../generateDS.py -f -o out2sup.py -s out2sub.py people
outfile, infile = popen2.popen2(cmd)
result = outfile.read()
outfile.close()
infile.close()
self.failUnless(len(result) == 0)
def test_2_compare_superclasses(self):
cmd = 'diff out1sup.py out2sup.py'
outfile, infile = popen2.popen2(cmd)
def test_3_compare_subclasses(self):
cmd = 'diff out1sub.py out2sub.py'
outfile, infile = popen2.popen2(cmd)
outfile, infile = popen2.popen2(cmd)
result = outfile.read()
outfile.close()
infile.close()
# Ignore the differing lines containing the date/time.
#self.failUnless(len(result) < 130 and result.find('Generated') > -1
self.failUnless(check_result(result))
def check_result(result):
flag1 = 0
flag2 = 0
lines = result.split('\n')
len1 = len(lines)
if len1 <= 5:
flag1 = 1
s1 = '\n'.join(lines[:4])
if s1.find('Generated') > -1:
flag2 = 1
return flag1 and flag2
USAGE_TEXT = """
Usage:
python test.py [options]
Options:
-h, --help Display this help message.
Example:
python test.py
"""
def usage():
http://www.davekuhlman.org/python_101.html 74/81
11/17/2017 Python 101 --- Introduction to Python
def usage():
print USAGE_TEXT
sys.exit(-1)
def main():
args = sys.argv[1:]
try:
opts, args = getopt.getopt(args, 'h', ['help'])
except:
usage()
relink = 1
for opt, val in opts:
if opt in ('-h', '--help'):
usage()
if len(args) != 0:
usage()
test()
if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')
Notes:
import unittest
class UnitTests02(unittest.TestCase):
def testFoo(self):
self.failUnless(False)
http://www.davekuhlman.org/python_101.html 75/81
11/17/2017 Python 101 --- Introduction to Python
def checkBar01(self):
self.failUnless(False)
class UnitTests01(unittest.TestCase):
# Note 1
def setUp(self):
print 'setting up UnitTests01'
def tearDown(self):
print 'tearing down UnitTests01'
def testBar01(self):
print 'testing testBar01'
self.failUnless(False)
def testBar02(self):
print 'testing testBar02'
self.failUnless(False)
def function_test_1():
name = 'mona'
assert not name.startswith('mo')
def make_suite():
suite = unittest.TestSuite()
# Note 2
suite.addTest(unittest.makeSuite(UnitTests01, sortUsing=compare_names))
# Note 3
suite.addTest(unittest.makeSuite(UnitTests02, prefix='check'))
# Note 4
suite.addTest(unittest.FunctionTestCase(function_test_1))
return suite
def main():
suite = make_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
main()
Notes:
1. If you run this code, you will notice that the setUp and tearDown methods in class
UnitTests01 are run before and after each test in that class.
2. We can control the order in which tests are run by passing a compare function
to the makeSuite function. The default is the cmp built-in function.
3. We can control which methods in a test fixture are selected to be run by
passing the optional argument prefix to the makeSuite function.
http://www.davekuhlman.org/python_101.html 76/81
11/17/2017 Python 101 --- Introduction to Python
4. If we have an existing function that we want to "wrap" and run as a unit test,
we can create a test case from a function with the FunctionTestCase function. If we
do that, notice that we use the assert statement to test and possibly cause
failure.
Without unit tests, corner cases may not be checked. This is especially
important, since Python does relatively little compile time error checking.
Unit tests facilitate a frequent and short design and implement and release
development cycle. See ONLamp.com -- Extreme Python --
http://www.onlamp.com/pub/a/python/2001/03/28/pythonnews.html and What
is XP -- http://www.xprogramming.com/what_is_xp.htm.
Designing the tests before writing the code is "a good idea".
Additional notes:
In a test class, instance methods setUp and tearDown are run automatically before
each and after each individual test.
In a test class, class methods setUpClass and tearDownClass are run automatically
once before and after all the tests in a class.
Module level functions setUpModule and tearDownModule are run before and after any
tests in a module.
In some cases you can also run tests directly from the command line. Do the
following for help:
9.4 doctest
For simple test harnesses, consider using doctest. With doctest you can (1) run a test
at the Python interactive prompt, then (2) copy and paste that test into a doc string
in your module, and then (3) run the tests automatically from within your module
under doctest.
There are examples and explanation in the standard Python documentation: 5.2
doctest -- Test interactive Python examples -- http://docs.python.org/lib/module-
doctest.html.
1. Run several tests in the Python interactive interpreter. Note that because doctest
looks for the interpreter's ">>>" prompt, you must use the standard
interpreter, and not, for example, IPython. Also, make sure that you include a
http://www.davekuhlman.org/python_101.html 77/81
11/17/2017 Python 101 --- Introduction to Python
line with the ">>>" prompt after each set of results; this enables doctest to
determine the extent of the test results.
2. Use copy and paste, to insert the tests and their results from your interactive
session into the docstrings.
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
Here is an example:
def f(n):
"""
Print something funny.
>>> f(1)
10
>>> f(2)
-10
>>> f(3)
0
"""
if n == 1:
return 10
elif n == 2:
return -10
else:
return 0
def test():
import doctest, test_doctest
doctest.testmod(test_doctest)
if __name__ == '__main__':
test()
And, here is the output from running the above test with the -v flag:
$ python test_doctest.py -v
Running test_doctest.__doc__
0 of 0 examples failed in test_doctest.__doc__
Running test_doctest.f.__doc__
Trying: f(1)
Expecting: 10
ok
Trying: f(2)
Expecting: -10
http://www.davekuhlman.org/python_101.html 78/81
11/17/2017 Python 101 --- Introduction to Python
ok
Trying: f(3)
Expecting: 0
ok
0 of 3 examples failed in test_doctest.f.__doc__
Running test_doctest.test.__doc__
0 of 0 examples failed in test_doctest.test.__doc__
2 items had no tests:
test_doctest
test_doctest.test
1 items passed all tests:
3 tests in test_doctest.f
3 tests in 3 items.
3 passed and 0 failed.
Test passed.
In order to use this API you must install the database adapter (interface module) for
your particular database, e.g. PostgreSQL, MySQL, Oracle, etc.
#!/usr/bin/env python
"""
Create a relational database and a table in it.
Add some records.
Read and display the records.
"""
import sys
import sqlite3
def create_table(db_name):
con = sqlite3.connect(db_name)
cursor = con.cursor()
cursor.execute('''CREATE TABLE plants
(name text, desc text, cat int)''')
cursor.execute(
'''INSERT INTO plants VALUES ('tomato', 'red and juicy', 1)''')
cursor.execute(
'''INSERT INTO plants VALUES ('pepper', 'green and crunchy', 2)''')
cursor.execute('''INSERT INTO plants VALUES ('pepper', 'purple', 2)''')
con.commit()
con.close()
def retrieve(db_name):
con = sqlite3.connect(db name)
http://www.davekuhlman.org/python_101.html 79/81
11/17/2017 Python 101 --- Introduction to Python
con sqlite3.connect(db_name)
cursor = con.cursor()
cursor.execute('''select * from plants''')
rows = cursor.fetchall()
print rows
print '-' * 40
cursor.execute('''select * from plants''')
for row in cursor:
print row
con.close()
def test():
args = sys.argv[1:]
if len(args) != 1:
sys.stderr.write('\nusage: test_db.py <db_name>\n\n')
sys.exit(1)
db_name = args[0]
create_table(db_name)
retrieve(db_name)
test()
More complex:
pip is becoming popular for installing and managing Python packages. See:
https://pypi.python.org/pypi/pip
Also, consider using virtualenv, especially if you suspect or worry that installing some
new package will alter the behavior of a package currently installed on your machine.
See: https://pypi.python.org/pypi/virtualenv. virtualenv creates a directory and sets
up a Python environment into which you can install and use Python packages without
changing your usual Python installation.
http://www.davekuhlman.org/python_101.html 80/81
11/17/2017 Python 101 --- Introduction to Python
Thanks to David Goodger for the following list or references. His "Code Like a
Pythonista: Idiomatic Python"
(http://python.net/~goodger/projects/pycon/2007/idiomatic/) is worth a careful
reading:
View document source. Generated on: 2014-10-05 20:00 UTC. Generated by Docutils
from reStructuredText source.
http://www.davekuhlman.org/python_101.html 81/81