100% found this document useful (5 votes)
16 views

Advanced Guide to Python 3 Programming, 2nd 2nd Edition John Hunt all chapter instant download

John

Uploaded by

dvingemajija
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
16 views

Advanced Guide to Python 3 Programming, 2nd 2nd Edition John Hunt all chapter instant download

John

Uploaded by

dvingemajija
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Download Full Version ebookmass - Visit ebookmass.

com

Advanced Guide to Python 3 Programming, 2nd 2nd


Edition John Hunt

https://ebookmass.com/product/advanced-guide-to-
python-3-programming-2nd-2nd-edition-john-hunt/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmass.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

A Beginners Guide to Python 3 Programming 2nd Edition John


Hunt

https://ebookmass.com/product/a-beginners-guide-to-
python-3-programming-2nd-edition-john-hunt/

ebookmass.com

Python Programming: 3 Books in 1: Ultimate Beginneru2019s,


Intermediate & Advanced Guide to Learn Python Step-by-Step

https://ebookmass.com/product/python-programming-3-books-
in-1-ultimate-beginners-intermediate-advanced-guide-to-learn-python-
step-by-step/
ebookmass.com

Learning Scientific Programming with Python 2nd Edition


Christian Hill

https://ebookmass.com/product/learning-scientific-programming-with-
python-2nd-edition-christian-hill-2/

ebookmass.com

Oxford Studies in Philosophy of Mind Volume 3 Uriah


Kriegel

https://ebookmass.com/product/oxford-studies-in-philosophy-of-mind-
volume-3-uriah-kriegel/

ebookmass.com
Vice in Ancient Philosophy Karen Margrethe Nielsen

https://ebookmass.com/product/vice-in-ancient-philosophy-karen-
margrethe-nielsen/

ebookmass.com

Tales From The Cafe (Before the Coffee Gets Cold, #2)
Toshikazu Kawaguchi

https://ebookmass.com/product/tales-from-the-cafe-before-the-coffee-
gets-cold-2-toshikazu-kawaguchi/

ebookmass.com

Finish Strong Dan Green

https://ebookmass.com/product/finish-strong-dan-green-2/

ebookmass.com

Life Cycle of Sustainable Packaging: From Design to End-


of-Life Rafael A. Auras

https://ebookmass.com/product/life-cycle-of-sustainable-packaging-
from-design-to-end-of-life-rafael-a-auras/

ebookmass.com

Introduction to the Theory of Complex Systems Stefan


Thurner

https://ebookmass.com/product/introduction-to-the-theory-of-complex-
systems-stefan-thurner/

ebookmass.com
Swami Vivekananda's Ved■ntic Cosmopolitanism Swami
Medhananda

https://ebookmass.com/product/swami-vivekanandas-vedantic-
cosmopolitanism-swami-medhananda/

ebookmass.com
Undergraduate Topics in Computer Science

John Hunt

Advanced Guide
to Python 3
Programming
Second Edition
Undergraduate Topics in Computer Science

Series Editor
Ian Mackie, University of Sussex, Brighton, UK

Advisory Editors
Samson Abramsky , Department of Computer Science, University of Oxford,
Oxford, UK
Chris Hankin , Department of Computing, Imperial College London, London,
UK
Mike Hinchey , Lero – The Irish Software Research Centre, University of
Limerick, Limerick, Ireland
Dexter C. Kozen, Department of Computer Science, Cornell University, Ithaca,
NY, USA
Andrew Pitts , Department of Computer Science and Technology, University of
Cambridge, Cambridge, UK
Hanne Riis Nielson , Department of Applied Mathematics and Computer
Science, Technical University of Denmark, Kongens Lyngby, Denmark
Steven S. Skiena, Department of Computer Science, Stony Brook University,
Stony Brook, NY, USA
Iain Stewart , Department of Computer Science, Durham University, Durham,
UK
Joseph Migga Kizza, College of Engineering and Computer Science, The
University of Tennessee-Chattanooga, Chattanooga, TN, USA
‘Undergraduate Topics in Computer Science’ (UTiCS) delivers high-quality instruc-
tional content for undergraduates studying in all areas of computing and information
science. From core foundational and theoretical material to final-year topics and
applications, UTiCS books take a fresh, concise, and modern approach and are ideal
for self-study or for a one- or two-semester course. The texts are all authored by
established experts in their fields, reviewed by an international advisory board, and
contain numerous examples and problems, many of which include fully worked
solutions.
The UTiCS concept relies on high-quality, concise books in softback format, and
generally a maximum of 275–300 pages. For undergraduate textbooks that are likely
to be longer, more expository, Springer continues to offer the highly regarded Texts
in Computer Science series, to which we refer potential authors.
John Hunt

Advanced Guide to Python 3


Programming
Second Edition
John Hunt
Midmarsh Technology Ltd.
Chippenham, Wiltshire, UK

ISSN 1863-7310 ISSN 2197-1781 (electronic)


Undergraduate Topics in Computer Science
ISBN 978-3-031-40335-4 ISBN 978-3-031-40336-1 (eBook)
https://doi.org/10.1007/978-3-031-40336-1

© Springer Nature Switzerland AG 2019, 2023

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of
the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology
now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
For Denise, my wife, my soulmate, my best
friend.
Preface to the Second Edition

This second edition represents a significant expansion of the material in the first
edition, as well as an update of that book from Python 3.7 to 3.12.
This book includes whole new sections on advanced language features, Reactive
Programming in Python and data analysts. New chapters on working with Tkinter,
on event handling with Tkinter and a simple drawing application using Tkinter have
been added. A new chapter on performance monitoring and profiling has also been
added. A chapter on pip and conda is included at the end of the book.
In all there are 18 completely new chapters that take you far further on your Python
journey. Enjoy the book and I hope you find it useful.

Chippenham, UK John Hunt

vii
Preface to the First Edition

Some of the key aspects of this book are


1. It assumes knowledge of Python 3 and of concepts such as functions, classes,
protocols, abstract base classes, decorators, iterables and collection types (such
as list and tuple).
2. However, the book assumes very little knowledge or experience of the topics
presented.
3. The book is divided into eleven topic areas: advanced language features,
Computer Graphics, games, testing, file input/output, database access, logging,
concurrency and parallelism, Reactive Programming, network programming and
data analytics.
4. Each topic in the book has an introductory chapter followed by chapters that
delve into that topic.
5. The book includes exercises at the end of most chapters.
6. All code examples (and exercise solutions) are provided on line in a GitHub
repository.

What You Need

You can of course just read this book; however following the examples in this book
will ensure that you get as much as possible out of the content. For this you will need
a computer.
Python is a cross-platform programming language, and as such you can use Python
on a Windows PC, a Linux box, an Apple Mac, etc. So you are not tied to a particular
type of operating system; you can use whatever you have available.
However you will need to install some software on that computer. At a minimum
you will need Python. The focus of this book is Python 3 so that is the version that
is assumed for all examples and exercises. As Python is available for a wide range

ix
x Preface to the First Edition

of platforms from Windows, to Mac OS and Linux, you will need to ensure that you
download the version for your operating system.
Python can be downloaded from the main Python website which can be found at
http://www.python.org/.

You will also need some form of editor to write your programs. There are numerous
generic programming editors available for different operating systems with VIM on
Linux, Notepad++ on Windows and Sublime Text on windows and Macs being
popular choices.
However, using an Integrated Development Environment (IDE) editor such as
PyCharm, Visual Studio Code or Spyder can make writing and running your programs
much easier.
However, this book does not assume any particular editor, IDE or environment
(other than Python 3 itself).

Conventions

Throughout this book you will find a number of conventions used for text styles.
These text styles distinguish between different kinds of information. Code words,
variable and Python values, used within the main body of the text, are shown using
a Courier font. A block of Python code is set out as shown here:
Preface to the First Edition xi

def draw_koch(size, depth):


if depth > 0:
for angle in ANGLES:
draw_koch(size / 3, depth - 1)
turtle.left(angle)
else:
turtle.forward(size)
# Draw three sides of snowflake
for_in range(3):
draw_koch(SIZE_OF_SNOWFLAKE, depth)
turtle.right(120)

Note that keywords and points of interest are shown in bold font.
Any command line or user input is shown in standard font as shown below, for
example:
Hello, world
Enter your name: John
Hello John

Example Code and Sample Solutions

The examples used in this book (along with sample solutions for the exercises at the
end of most chapters) are available in a GitHub repository. GitHub provides a web
interface to Git, as well as a server environment hosting Git.
Git is a version control system typically used to manage source code files (such
as those used to create systems in programming languages such as Python but also
Java, C#, C++ and Scala). Systems such as Git are very useful for collaborative
development as they allow multiple people to work on an implementation and to
merge their work together. They also provide a useful historical view of the code
(which also allows developers to roll back changes if modifications prove to be
unsuitable).
The GitHub repository for this book can be found at:
• https://github.com/johnehunt/advancedpython3_2nd
If you already have Git installed on your computer, then you can clone (obtain a
copy of) the repository locally using:
git clone https://github.com/johnehunt/advancedpyth
on3_2nd.git
If you do not have Git, then you can obtain a zip file of the examples using
https://github.com/johnehunt/advancedpython3_2nd/arc
hive/refs/heads/main.zip
xii Preface to the First Edition

You can of course install Git yourself if you wish. To do this, see https://git-scm.
com/downloads. Versions of the Git client for Mac OS, Windows and Linux/Unix
are available here.
However, many IDEs such as PyCharm come with Git support and so offer another
approach to obtaining a Git repository.
For more information on Git see http://git-scm.com/doc. This Git guide
provides a very good primer and is highly recommended.

Acknowledgement I would like to thank Phoebe Hunt for creating the pixel images used for the
Starship Meteors game in Chap. 22.
Contents

1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Useful Python Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Part I Advanced Language Features


2 Python Type Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Pythons Type System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 The Challenge for Python Developers . . . . . . . . . . . . . . . . . . . . . . 8
2.4 Static Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.5 Python Type Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.6 Type Hint Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.7 Type Hints for Multiple Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.8 The Self Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.9 The Benefits of Type Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.11 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3 Class Slots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2 The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.3 Slots to the Rescue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.4 Performance Benefits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.5 Why Not Use Slots? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.6 Online Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4 Weak References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.2 How Garbage Collection Works: Reference Counting . . . . . . . . 23
4.3 Weak References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.4 When to Use Weak References . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

xiii
xiv Contents

4.5 The Weakref Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26


4.6 Creating Weak References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.7 Retrieving Objects from Weak References . . . . . . . . . . . . . . . . . . 28
4.8 The WeakValueDicitonary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.9 WeakKeyDictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.10 Proxy Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.11 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5 Data Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.2 A Traditional Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.3 Defining Data Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.4 Defining Additional Behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.5 The Dataclass Decorator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.6 Custom Factory for Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.7 Immutable Dataclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.8 Data Classes and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.9 Post Initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
5.10 Initialisation Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
5.11 Positional Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.12 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
6 Structural Pattern Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
6.2 The Match Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
6.3 Matching Classes with Positional Attributes . . . . . . . . . . . . . . . . . 50
6.4 Matching Against Standard Classes . . . . . . . . . . . . . . . . . . . . . . . . 51
6.5 Online Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
7 Working with pprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
7.2 The pprint Data Printer Module . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
7.3 Basic pprint Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
7.4 Changing the Width . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
7.5 Changing the Depth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
7.6 Managing the Indentation Level . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
7.7 Reducing Line Breaks Using Compact . . . . . . . . . . . . . . . . . . . . . 59
7.8 The pformat Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
7.9 The saferepr() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
7.10 Using the PrettyPrinter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
7.11 Online Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
8 Shallow v Deep Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
8.2 Copying a List of Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
8.3 The Problem with Copying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Contents xv

8.4 The Copy Module to the Rescue . . . . . . . . . . . . . . . . . . . . . . . . . . . 68


8.5 Using the deepcopy() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
8.6 Online Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9 The __init__ Versus __new__ and __call . . . . . . . . . . . . . . . . . . . . . . . . . 71
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
9.2 The __new__ and __init__ Methods . . . . . . . . . . . . . . . . . . . . . . . 71
9.3 The __new__ Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
9.4 When to Use the __new__ Method . . . . . . . . . . . . . . . . . . . . . . . . . 73
9.5 Using __new__ to Create a Singleton Object . . . . . . . . . . . . . . . . 74
9.6 The __init__ Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
9.7 Can __new__ and __init__ Be Used Together? . . . . . . . . . . . . . . 76
9.8 The __call__ Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
9.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
10 Python Metaclasses and Meta Programming . . . . . . . . . . . . . . . . . . . . . 79
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
10.2 Metaprogramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
10.3 Decorators as a Form of Metaprogramming . . . . . . . . . . . . . . . . . 81
10.4 Metaclasses for Metaprogramming . . . . . . . . . . . . . . . . . . . . . . . . 83
10.4.1 Singleton Metaclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
10.5 Exec and Eval for Metaprogramming . . . . . . . . . . . . . . . . . . . . . . 85
10.5.1 The exec() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
10.5.2 The eval() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
10.5.3 eval Versus exec() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

Part II Computer Graphics and GUIs


11 Introduction to Computer Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
11.2 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
11.3 The Graphical Computer Era . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
11.4 Interactive and Non Interactive Graphics . . . . . . . . . . . . . . . . . . . . 93
11.5 Pixels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
11.6 Bit Map Versus Vector Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
11.7 Buffering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
11.8 Python and Computer Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
11.9 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
11.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
12 Python Turtle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
12.2 The Turtle Graphics Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
12.2.1 The Turtle Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
12.2.2 Basic Turtle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
12.2.3 Drawing Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
12.2.4 Filling Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
xvi Contents

12.3 Other Graphics Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105


12.4 3D Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
12.4.1 PyOpenGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
12.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
12.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
13 Computer Generated Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
13.1 Creating Computer Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
13.2 A Computer Art Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
13.3 Fractals in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
13.4 The Koch Snowflake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
13.5 Mandelbrot Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
13.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
13.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
14 Introduction to Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
14.2 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
14.3 Plot Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
14.4 Matplotlib Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
14.4.1 Backend Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
14.4.2 The Artist Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
14.4.3 The Scripting Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
14.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
15 Graphing with Matplotlib Pyplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
15.2 The pyplot API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
15.3 Line Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
15.3.1 Coded Format Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
15.4 Scatter Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
15.4.1 When to Use Scatter Graphs . . . . . . . . . . . . . . . . . . . . . 134
15.5 Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
15.5.1 Expanding Segments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
15.5.2 When to Use Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . 138
15.6 Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
15.6.1 Horizontal Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
15.6.2 Coloured Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
15.6.3 Stacked Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
15.6.4 Grouped Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
15.7 Figures and Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
15.8 3D Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
15.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Contents xvii

16 Graphical User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151


16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
16.2 GUIs and WIMPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
16.3 Windowing Frameworks for Python . . . . . . . . . . . . . . . . . . . . . . . . 153
16.3.1 Platform-Independent GUI Libraries . . . . . . . . . . . . . . 154
16.3.2 Platform-Specific GUI Libraries . . . . . . . . . . . . . . . . . . 154
16.4 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
17 Tkinter GUI Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
17.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
17.2 Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
17.3 Windows as Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
17.4 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
17.4.1 The Tk Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
17.4.2 TK Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
17.4.3 The TopLevel Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
17.4.4 The Frame Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
17.4.5 Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
17.4.6 The Canvas Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
17.5 The Class Inheritance Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
17.5.1 Layout Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
17.6 A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
17.7 Tkinter Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
17.7.1 Mac Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
17.7.2 Windows Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
17.8 GUI Builders for Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
17.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
17.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
18 Events in Tkinter User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
18.2 Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
18.3 What is Event Handling? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
18.4 What Are Event Handlers? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
18.5 Event Binders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
18.6 Virtual Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
18.7 Event Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
18.8 What Types of Event Are There? . . . . . . . . . . . . . . . . . . . . . . . . . . 174
18.9 Binding an Event to an Event Handler . . . . . . . . . . . . . . . . . . . . . . 175
18.10 Implementing Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
18.11 An Interactive GUI Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
18.12 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
18.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
xviii Contents

19 PyDraw Tkinter Example Application . . . . . . . . . . . . . . . . . . . . . . . . . . 185


19.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
19.2 The PyDraw Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
19.3 The Structure of the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
19.3.1 Model, View and Controller Architecture . . . . . . . . . . 188
19.3.2 PyDraw MVC Architecture . . . . . . . . . . . . . . . . . . . . . . 189
19.3.3 Additional Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
19.3.4 Object Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
19.4 The Interactions Between Objects . . . . . . . . . . . . . . . . . . . . . . . . . 191
19.4.1 The PyDrawApp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
19.5 The PyDrawView Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
19.5.1 Changing the Application Mode . . . . . . . . . . . . . . . . . . 193
19.5.2 Adding a Graphic Object . . . . . . . . . . . . . . . . . . . . . . . . 193
19.6 The Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
19.6.1 The PyDrawConstants Class . . . . . . . . . . . . . . . . . . . . . 194
19.6.2 The PyDrawView Class . . . . . . . . . . . . . . . . . . . . . . . . . 195
19.6.3 The PyDrawMenuBar Class . . . . . . . . . . . . . . . . . . . . . . 196
19.6.4 The PyDrawController Class . . . . . . . . . . . . . . . . . . . . . 196
19.6.5 The DrawingModel Class . . . . . . . . . . . . . . . . . . . . . . . . 197
19.6.6 The DrawingView Class . . . . . . . . . . . . . . . . . . . . . . . . . 198
19.6.7 The DrawingController Class . . . . . . . . . . . . . . . . . . . . . 198
19.6.8 The Figure Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
19.6.9 The Square Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
19.6.10 The Circle Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
19.6.11 The Line Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
19.6.12 The Text Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
19.7 Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
19.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

Part III Computer Games


20 Introduction to Games Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
20.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
20.2 Games Frameworks and Libraries . . . . . . . . . . . . . . . . . . . . . . . . . 205
20.3 Python Games Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
20.4 Using Pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
20.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
21 Building Games with Pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
21.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
21.2 The Display Surface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
21.3 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
21.3.1 Event Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
21.3.2 Event Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
21.3.3 The Event Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Contents xix

21.4 A First pygame Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214


21.5 Further Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
21.6 A More Interactive pygame Application . . . . . . . . . . . . . . . . . . . . 219
21.7 Alternative Approach to Processing Input Devices . . . . . . . . . . . 221
21.8 pygame Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
21.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
22 StarshipMeteors Pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
22.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
22.2 Creating a Spaceship Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
22.3 The Main Game Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
22.4 The GameObject Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
22.5 Displaying the Starship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
22.6 Moving the Spaceship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
22.7 Adding a Meteor Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
22.8 Moving the Meteors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
22.9 Identifying a Collision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
22.10 Identifying a Win . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
22.11 Increasing the Number of Meteors . . . . . . . . . . . . . . . . . . . . . . . . . 238
22.12 Pausing the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
22.13 Displaying the Game Over Message . . . . . . . . . . . . . . . . . . . . . . . 239
22.14 The StarshipMeteors Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
22.15 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
22.16 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244

Part IV Testing
23 Introduction to Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
23.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
23.2 Types of Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
23.3 What Should Be Tested? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
23.4 Types of Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
23.4.1 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
23.4.2 Integration Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
23.4.3 System Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
23.4.4 Installation/Upgrade Testing . . . . . . . . . . . . . . . . . . . . . 252
23.4.5 Smoke Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
23.5 Automating Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
23.6 Test-Driven Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
23.6.1 The TDD Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
23.6.2 Test Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
23.6.3 Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
23.7 Design for Testability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
23.7.1 Testability Rules of Thumb . . . . . . . . . . . . . . . . . . . . . . 255
23.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
23.9 Book Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
xx Contents

24 PyTest Testing Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257


24.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
24.2 What is PyTest? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
24.3 Setting up PyTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
24.4 A Simple PyTest Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
24.5 Working with PyTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
24.6 Parameterised Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
24.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
24.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
25 Mocking for Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
25.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
25.2 Why Mock? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
25.3 What is Mocking? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
25.4 Common Mocking Framework Concepts . . . . . . . . . . . . . . . . . . . 273
25.5 Mocking Frameworks for Python . . . . . . . . . . . . . . . . . . . . . . . . . . 274
25.6 The Unittest.Mock Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
25.6.1 Mock and Magic Mock Classes . . . . . . . . . . . . . . . . . . . 275
25.6.2 The Patchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
25.6.3 Mocking Returned Objects . . . . . . . . . . . . . . . . . . . . . . . 277
25.6.4 Validating Mocks Have Been Called . . . . . . . . . . . . . . . 278
25.7 Mock and MagicMock Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
25.7.1 Naming Your Mocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
25.7.2 Mock Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
25.7.3 Attributes on Mock Classes . . . . . . . . . . . . . . . . . . . . . . 279
25.7.4 Mocking Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
25.7.5 Mocking Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
25.7.6 Raising Exceptions with Mocks . . . . . . . . . . . . . . . . . . . 281
25.7.7 Applying Patch to Every Test Method . . . . . . . . . . . . . 281
25.7.8 Using Patch as a Context Manager . . . . . . . . . . . . . . . . 281
25.8 Mock Where You Use It . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
25.9 Patch Order Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
25.10 How Many Mocks? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
25.11 Mocking Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
25.12 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
25.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284

Part V File Input/Output


26 Introduction to Files, Paths and IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
26.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
26.2 File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
26.3 Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
26.4 File Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Contents xxi

26.5 Sequential Access versus Random Access . . . . . . . . . . . . . . . . . . 296


26.6 Files and I/O in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
26.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
27 Reading and Writing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
27.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
27.2 Obtaining References to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
27.3 Reading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
27.4 File Contents Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
27.5 Writing Data to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
27.6 Using Files and with Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
27.7 The Fileinput Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
27.8 Renaming Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
27.9 Deleting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
27.10 Random Access Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
27.11 Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
27.12 Temporary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
27.13 Working with Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
27.14 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
27.15 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
28 Stream IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
28.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
28.2 What is a Stream? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
28.3 Python Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
28.4 IOBase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
28.5 Raw IO/UnBuffered IO Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
28.6 Binary IO/Buffered IO Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
28.7 Text Stream Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
28.8 Stream Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
28.9 Closing Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
28.10 Returning to the Open() Function . . . . . . . . . . . . . . . . . . . . . . . . . . 322
28.11 Online Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
28.12 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
29 Working with CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
29.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
29.2 CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
29.2.1 The CSV Writer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
29.2.2 The CSV Reader Class . . . . . . . . . . . . . . . . . . . . . . . . . . 327
29.2.3 The CSV DictWriter Class . . . . . . . . . . . . . . . . . . . . . . . 328
29.2.4 The CSV DictReader Class . . . . . . . . . . . . . . . . . . . . . . 329
29.3 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
29.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
xxii Contents

30 Working with Excel Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333


30.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
30.2 Excel Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
30.3 The Openpyxl. Workbook Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
30.4 The Openpyxl. WorkSheet Objects . . . . . . . . . . . . . . . . . . . . . . . . . 334
30.5 Working with Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
30.6 Sample Excel File Creation Application . . . . . . . . . . . . . . . . . . . . 335
30.7 Loading a Workbook from an Excel File . . . . . . . . . . . . . . . . . . . . 336
30.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
30.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
31 Regular Expressions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
31.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
31.2 What Are Regular Expressions? . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
31.3 Regular Expression Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
31.3.1 Pattern Metacharacters . . . . . . . . . . . . . . . . . . . . . . . . . . 342
31.3.2 Special Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
31.3.3 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
31.4 The Python re Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
31.5 Working with Python Regular Expressions . . . . . . . . . . . . . . . . . . 345
31.5.1 Using Raw Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
31.5.2 Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
31.5.3 The Match Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
31.5.4 The search() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
31.5.5 The match() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
31.5.6 The Difference Between Matching
and Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
31.5.7 The finadall() Function . . . . . . . . . . . . . . . . . . . . . . . . . . 349
31.5.8 The finditer() Function . . . . . . . . . . . . . . . . . . . . . . . . . . 349
31.5.9 The split() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
31.5.10 The sub() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
31.5.11 The compile() Function . . . . . . . . . . . . . . . . . . . . . . . . . . 351
31.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
31.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354

Part VI Database Access


32 Introduction to Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
32.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
32.2 What Is a Database? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
32.2.1 Data Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
32.2.2 The Database Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
32.3 SQL and Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
32.4 Data Manipulation Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
32.5 Transactions in Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
32.6 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
Contents xxiii

33 Python DB-API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369


33.1 Accessing a Database from Python . . . . . . . . . . . . . . . . . . . . . . . . 369
33.2 The DB-API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
33.2.1 The Connect Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
33.2.2 The Connection Object . . . . . . . . . . . . . . . . . . . . . . . . . . 370
33.2.3 The Cursor Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
33.2.4 Mappings from Database Types to Python Types . . . . 372
33.2.5 Generating Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
33.2.6 Row Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
33.3 Transactions in PyMySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
33.4 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
34 PyMySQL Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
34.1 The PyMySQL Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
34.2 Working with the PyMySQL Module . . . . . . . . . . . . . . . . . . . . . . 377
34.2.1 Importing the Module . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
34.2.2 Connect to the Database . . . . . . . . . . . . . . . . . . . . . . . . . 378
34.2.3 Obtaining the Cursor Object . . . . . . . . . . . . . . . . . . . . . . 379
34.2.4 Using the Cursor Object . . . . . . . . . . . . . . . . . . . . . . . . . 379
34.2.5 Obtaining Information About the Results . . . . . . . . . . . 380
34.2.6 Fetching Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
34.2.7 Close the Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
34.3 Complete PyMySQL Query Example . . . . . . . . . . . . . . . . . . . . . . 381
34.4 Inserting Data to the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
34.5 Updating Data in the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
34.6 Deleting Data in the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
34.7 Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
34.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
34.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387

Part VII Logging


35 Introduction to Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
35.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
35.2 Why Log? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
35.3 What is the Purpose of Logging? . . . . . . . . . . . . . . . . . . . . . . . . . . 392
35.4 What Should You Log? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
35.5 What not to Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
35.6 Why not Just Use Print? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
35.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
36 Logging in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
36.1 The Logging Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
36.2 The Logger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
36.3 Controlling the Amount of Information Logged . . . . . . . . . . . . . . 399
36.4 Logger Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
xxiv Contents

36.5 Default Logger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402


36.6 Module Level Loggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
36.7 Logger Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
36.8 Formatters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
36.8.1 Formatting Log Messages . . . . . . . . . . . . . . . . . . . . . . . . 406
36.8.2 Formatting Log Output . . . . . . . . . . . . . . . . . . . . . . . . . . 406
36.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
36.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
37 Advanced Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
37.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
37.2 Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
37.2.1 Setting the Root Output Handler . . . . . . . . . . . . . . . . . . 411
37.2.2 Programmatically Setting the Handler . . . . . . . . . . . . . 412
37.2.3 Multiple Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
37.3 Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
37.4 Logger Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
37.5 Performance Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
37.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419

Part VIII Concurrency and Parallelism


38 Introduction to Concurrency and Parallelism . . . . . . . . . . . . . . . . . . . . 423
38.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
38.2 Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
38.3 Parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
38.4 Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
38.5 Grid Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
38.6 Concurrency and Synchronisation . . . . . . . . . . . . . . . . . . . . . . . . . 428
38.7 Object Orientation and Concurrency . . . . . . . . . . . . . . . . . . . . . . . 428
38.8 Threads V Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
38.9 Some Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
38.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
39 Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
39.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
39.2 Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
39.2.1 Thread States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
39.2.2 Creating a Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
39.2.3 Instantiating the Thread Class . . . . . . . . . . . . . . . . . . . . 435
39.3 The Thread Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
39.4 The Threading Module Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 438
39.5 Passing Arguments to a Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
39.6 Extending the Thread Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
39.7 Daemon Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Contents xxv

39.8 Naming Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442


39.9 Thread Local Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
39.10 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
39.11 The Global Interpreter Lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
39.12 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
39.13 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
40 MultiProcessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
40.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
40.2 The Process Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
40.3 Working with the Process Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
40.4 Alternative Ways to Start a Process . . . . . . . . . . . . . . . . . . . . . . . . 453
40.5 Using a Pool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
40.6 Exchanging Data Between Processes . . . . . . . . . . . . . . . . . . . . . . . 458
40.7 Sharing State Between Processes . . . . . . . . . . . . . . . . . . . . . . . . . . 460
40.7.1 Process Shared Memory . . . . . . . . . . . . . . . . . . . . . . . . . 460
40.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
40.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
41 Inter Thread/Process Synchronisation . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
41.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
41.2 Using a Barrier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
41.3 Event Signalling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
41.4 Synchronising Concurrent Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
41.5 Python Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
41.6 Python Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
41.7 Python Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
41.8 The Concurrent Queue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
41.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
41.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
42 Futures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
42.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
42.2 The Need for a Future . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
42.3 Futures in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
42.3.1 Future Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
42.3.2 Simple Example Future . . . . . . . . . . . . . . . . . . . . . . . . . . 483
42.4 Running Multiple Futures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
42.4.1 Waiting for All Futures to Complete . . . . . . . . . . . . . . . 486
42.4.2 Processing Results as Completed . . . . . . . . . . . . . . . . . 488
42.5 Processing Future Results Using a Callback . . . . . . . . . . . . . . . . . 489
42.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
42.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
xxvi Contents

43 Concurrency with AsyncIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493


43.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
43.2 Asynchronous IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
43.3 Async IO Event Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
43.4 The Async and Await Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
43.4.1 Using Async and Await . . . . . . . . . . . . . . . . . . . . . . . . . . 496
43.5 Async IO Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
43.6 Running Multiple Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
43.6.1 Collating Results from Multiple Tasks . . . . . . . . . . . . . 500
43.6.2 Handling Task Results as They Are Made
Available . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
43.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
43.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
44 Performance Monitoring and Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . 505
44.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
44.2 Why Monitor Performance and Memory? . . . . . . . . . . . . . . . . . . . 505
44.3 Performance Monitoring and Profiling . . . . . . . . . . . . . . . . . . . . . 506
44.4 Performance Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
44.4.1 The Time Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
44.4.2 The Timeit Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
44.4.3 The Psutil Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
44.5 Python Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
44.5.1 The cProfile Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
44.5.2 The Line_Profiler Module . . . . . . . . . . . . . . . . . . . . . . . 511
44.5.3 The Memory_Profiler Module . . . . . . . . . . . . . . . . . . . . 512
44.5.4 Additional Third-Party Libraries . . . . . . . . . . . . . . . . . . 512
44.6 Profiling with cProfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
44.7 Memory Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
44.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517

Part IX Reactive Programming


45 Reactive Programming Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
45.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
45.2 What Is a Reactive Application? . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
45.3 The ReactiveX Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
45.4 The Observer Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
45.5 Hot and Cold Observables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
45.6 Differences Between Event Driven Programming
and Reactive Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
45.7 Advantages of Reactive Programming . . . . . . . . . . . . . . . . . . . . . . 525
45.8 Disadvantages of Reactive Programming . . . . . . . . . . . . . . . . . . . 525
45.9 The RxPy Reactive Programming Framework . . . . . . . . . . . . . . . 526
45.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
Contents xxvii

46 RxPy Observables, Observers and Subjects . . . . . . . . . . . . . . . . . . . . . . 527


46.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
46.2 RxPy Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
46.3 Observables in RxPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
46.4 Observers in RxPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
46.5 Multiple Subscribers/Observers . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
46.6 Subjects in RxPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
46.7 Observer Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
46.7.1 Available Schedulers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
46.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
46.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
47 RxPy Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
47.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
47.2 Reactive Programming Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 537
47.3 Piping Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
47.4 Creational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
47.5 Transformational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
47.6 Combinatorial Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
47.7 Filtering Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
47.8 Mathematical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
47.9 Chaining Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
47.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
47.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546

Part X Network Programming


48 Introduction to Sockets and Web Services . . . . . . . . . . . . . . . . . . . . . . . 551
48.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
48.2 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
48.3 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
48.4 Addressing Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
48.5 Localhost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
48.6 Port Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
48.7 IPv4 Versus IPv6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
48.8 Sockets and Web Services in Python . . . . . . . . . . . . . . . . . . . . . . . 555
48.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
49 Sockets in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
49.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
49.2 Socket to Socket Communication . . . . . . . . . . . . . . . . . . . . . . . . . . 557
49.3 Setting up a Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
49.4 An Example Client Server Application . . . . . . . . . . . . . . . . . . . . . 558
49.4.1 The System Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
49.4.2 Implementing the Server Application . . . . . . . . . . . . . . 559
xxviii Contents

49.4.3 Socket Types and Domains . . . . . . . . . . . . . . . . . . . . . . . 560


49.4.4 Implementing the Client Application . . . . . . . . . . . . . . 561
49.5 The Socketserver Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
49.6 Http Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
49.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
49.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
50 Web Services in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
50.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
50.2 RESTful Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
50.3 A RESTful API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
50.4 Python Web Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
50.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
51 Flask Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
51.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
51.2 Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
51.3 Hello World in Flask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
51.3.1 Using JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
51.4 Implementing a Flask Web Service . . . . . . . . . . . . . . . . . . . . . . . . 577
51.4.1 A Simple Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
51.4.2 Providing Routing Information . . . . . . . . . . . . . . . . . . . 577
51.5 Running the Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
51.6 Invoking the RESTFul Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
51.6.1 The Final Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
51.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
52 Flask Bookshop Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
52.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
52.2 Building a Flask Bookshop Service . . . . . . . . . . . . . . . . . . . . . . . . 583
52.3 The Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
52.4 The Domain Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
52.5 Encoding Books into JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
52.6 Setting Up the GET Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
52.7 Deleting a Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
52.8 Adding a New Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
52.9 Updating a Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
52.10 What Happens if We Get It Wrong? . . . . . . . . . . . . . . . . . . . . . . . . 593
52.11 Bookshop Services Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
52.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596

Part XI Data Science: Data Analytics and Machine Learning


53 Introduction to Data Science . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
53.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
53.2 Data Science . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
53.3 Data Science Tools and Techniques . . . . . . . . . . . . . . . . . . . . . . . . 602
Contents xxix

53.4 Data Analytics Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604


53.5 Python and Data Science . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
53.6 Machine Learning for Data Science . . . . . . . . . . . . . . . . . . . . . . . . 607
53.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
54 Pandas and Data Analytics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
54.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
54.2 The Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
54.2.1 The UK Government COVID Data Set . . . . . . . . . . . . . 611
54.2.2 The Google Mobility Data Set . . . . . . . . . . . . . . . . . . . . 613
54.3 Python Pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
54.3.1 Pandas Series and DataFrames . . . . . . . . . . . . . . . . . . . . 615
54.4 Loading and Analysing UK COVID Data Set . . . . . . . . . . . . . . . . 616
54.5 Loading the Google Mobility Data Set . . . . . . . . . . . . . . . . . . . . . 621
54.6 Merging Two DataFrames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
54.7 Analysing the Combined Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
54.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
55 Alternatives to Pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
55.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
55.2 Comparing Pandas 2.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
55.3 Pandas 1.x v 2.x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
55.4 Pandas Versus Other Libraries and Tools . . . . . . . . . . . . . . . . . . . . 630
55.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
56 Machine Learning in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
56.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
56.2 The Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
56.3 SciKitLearn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
56.4 The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
56.5 Using Regression Supervised Learning Systems . . . . . . . . . . . . . 636
56.6 K-Nearest Neighbour Regressor . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
56.7 Decision Tree Regressor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
56.8 Random Forest Regressor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
56.9 Summary of Metrics Obtained . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
56.10 Creating the Regressor Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
56.11 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
57 Pip and Conda Virtual Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
57.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
57.2 Virtual Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
57.3 Working with Pip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
57.3.1 Activating a Pip Environment . . . . . . . . . . . . . . . . . . . . 644
57.3.2 Installing Modules Using Pip . . . . . . . . . . . . . . . . . . . . . 645
57.3.3 Deactivating a Pip Environment . . . . . . . . . . . . . . . . . . 646
57.3.4 Check Version of Pip . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
57.3.5 Installing Modules into a Pip Environment . . . . . . . . . 646
xxx Contents

57.3.6 Freezing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647


57.4 Conda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
57.5 Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
57.5.1 Installing Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
57.6 Working with Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
57.6.1 Checking the Conda Version . . . . . . . . . . . . . . . . . . . . . 651
57.6.2 Updating Conda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
57.6.3 Creating a Conda Environment . . . . . . . . . . . . . . . . . . . 652
57.6.4 Listing Available Conda Environments . . . . . . . . . . . . 653
57.6.5 Activating a Conda Environment . . . . . . . . . . . . . . . . . . 654
57.6.6 Deactivating a Conda Environment . . . . . . . . . . . . . . . . 655
57.6.7 Listing the Modules Loaded into a Conda
Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
57.6.8 Removing an Anaconda Environment . . . . . . . . . . . . . 656
57.6.9 Installing a Module into a Conda Environment . . . . . . 656
57.7 Anaconda in PyCharm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
57.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
Chapter 1
Introduction

1.1 Introduction

I have heard many people over the years say that Python is an easy language to learn
and that Python is also a simple language.
To some extent both of these statements are true; but only to some extent.
While the core of the Python language is easy to lean and relatively simple (in
part thanks to its consistency), the sheer richness of the language constructs and
flexibility available can be overwhelming. In addition the Python environment, its
eco system, the range of libraries available, the often competing options available,
etc., can make moving to the next-level daunting.
Once you have learned the core elements of the language such as how classes
and inheritance work, how functions work, what are protocols and Abstract Base
Classes, etc. where do you go next?
The aim of this book is to delve into those next steps. The book is organised into
eleven different topics:
1. Advanced Language Features. The first section in the book covers topics
that are often missed out from introductory Python books such as slots, weak
references __init__() versus __new__() and metaclasses.
2. Computer Graphics. The book covers Computer Graphics and Computer
Generated Art in Python as well as graphical user interfaces and graphing/
charting via Matplotlib.
3. Games Programming. This topic is covered using the pygame library.
4. Testing and Mocking. Testing is an important aspect of any software develop-
ment; this book introduces testing in general and the PyTest module in detail.
It also considers mocking within testing including what and when to mock.

© Springer Nature Switzerland AG 2023 1


J. Hunt, Advanced Guide to Python 3 Programming,
Undergraduate Topics in Computer Science,
https://doi.org/10.1007/978-3-031-40336-1_1
2 1 Introduction

5. File Input/Output. The book covers text file reading and writing as well as
reading and writing CSV and Excel files. Although not strictly related to file
input, regulator expressions are included in this section as they can be used to
process textual data held in files.
6. Database Access. The book introduces databases and relational database in
particular. It then presents the Python DB-API database access standard and
one implementation of this standard, the PyMySQL module used to access a
MySQL database.
7. Logging. An often missed topic is that of logging. The book therefore introduces
logging the need for logging, what to log and what not to log as well as the Python
logging module.
8. Concurrency and Parallelism. The book provides extensive coverage of
concurrency topics including threads, processes and inter-thread or process
synchronisation. It also presents futures and AsyncIO.
9. Reactive Programming. This section of the book introduces Reactive Program-
ming using the PyRx Reactive Programming library.
10. Network Programming. The book introduces socket and web service commu-
nications in Python. It looks at both the Flask and the Django web service
libraries.
11. Data Analytics. A very hot topic for any potential Python programmer is data
analytics (and the related use of machine learning). The book concludes by
introducing these topics and there Pandas and scikit-learn (or SK-learn as it is
sometimes known) libraries.
Each section is introduced by a chapter providing the background and key concepts
of that topic. Subsequent chapters then cover various aspects of the topic.
For example, the second topic covered is on Computer Graphics. This section
has an introductory chapter on Computer Graphics in general. It then introduces the
Turtle Graphics Python library which can be used to generate a graphical display.
The following chapter considers the subject of Computer Generated Art and
uses the Turtle Graphics library to illustrate these ideas. Thus several examples
are presented that might be considered art. The chapter concludes by presenting the
well-known Koch Snowflake and the Mandelbrot Fractal set.
This is followed by a chapter presenting the Matplotlib library used for generating
2D and 3D charts and graphs (such as a line chart, bar chart or scatter graph).
The section concludes with a chapter on graphical user interfaces (or GUIs) using
the wxpython library. This chapter explores what we mean by a GUI and some of
the alternatives available in Python for creating a GUI.
Other topics follow a similar pattern.
Each programming or library-oriented chapter also includes numerous sample
programs that can be downloaded from the GitHub repository and executed. These
chapters also include one or more end of chapter exercises (with sample solutions
also in the GitHub repository).
1.2 Useful Python Resources 3

The topics within the book can be read mostly independently of each other. This
allows the reader to dip into subject areas as and when required. For example, the
File Input/Output section and the Database Access section can read independently
of each other (although in this case assessing both technologies may be useful in
selecting an appropriate approach to adopt for the long-term persistent storage of
data in a particular system).
Within each section there are usually dependencies; for example, it is neces-
sary to understand pygame library from the ‘Building Games with pygame’ intro-
ductory chapter, before exploring the worked case study presented by the chapter
on the StarshipMeteors game. Similarly it is necessary to have read the threading
and multiprocessing chapters before reading the inter-thread/process synchronisation
chapter.

1.2 Useful Python Resources

There are a wide range of resources on the web for Python; we will highlight a few
here that you should bookmark. We will not keep referring to these to avoid repetition
but you can refer back to this section whenever you need to:
• https://en.wikipedia.org/wiki/Python_Software_Foundation Python Software
Foundation.
• https://docs.python.org/3/ The main Python 3 documentation site. It contains
tutorials, library references, set up and installation guides as well as Python
how-tos.
• https://docs.python.org/3/library/index.html A list of all the built-in features for
the Python language—this is where you can find online documentation for the
various class and functions that we will be using throughout this book.
• https://pymotw.com/3/ the Python 3 Module of the week site. This site contains
many, many Python modules with short examples and explanations of what the
modules do. A Python module is a library of features that build on and expand
the core Python language. For example, if you are interested in building games
using Python then pygame is a module specifically designed to make this easier.
• https://www.fullstackpython.com/email.html is a monthly newsletter that
focusses on a single Python topic each month, such as a new library or module.
• http://www.pythonweekly.com/ is a free weekly summary of the latest Python
articles, projects, videos and upcoming events.
Each section of the book will provide additional online references relevant to the
topic being discussed.
Part I
Advanced Language Features
Chapter 2
Python Type Hints

2.1 Introduction

Python is a dynamically typed language right—well yes it is however there is a


feature known as Type Hints that allows typing information to be provided when
functions and methods are defined. These Type Hints are extremely useful and can
help a developer understand what types are expected by a function or a method and
indeed what types are likely to be returned.
Recent versions of Python, including 3.10 and 3.11, have increased the support
for Type Hints so that they are now quite usable. These can be used by analysis tools
and IDEs to help developers create more stable and reliable applications.

2.2 Pythons Type System

Many people consider Python to be an untyped programming language. However,


that is not quite true. The type system in Python can be referred to as representing
a dynamically typed programming language. That is a variable holds a value and
the type of that value is known and understood by the language. At runtime Python
checks that what you are trying to do is valid given the types involved. For example,
you can use the type() function to find out what type of thing a variable holds at
any point in time:
a_variable = 42
print(f'a_variable type = {type(a_variable)} = {a_variable}')
a_variable = 1.345
print(f'a_variable type = {type(a_variable)} = {a_variable}')
a_variable = "Hello"
print(f'a_variable type = {type(a_variable)} = {a_variable}')
a_variable = True
print(f'a_variable type = {type(a_variable)} = {a_variable}')

© Springer Nature Switzerland AG 2023 7


J. Hunt, Advanced Guide to Python 3 Programming,
Undergraduate Topics in Computer Science,
https://doi.org/10.1007/978-3-031-40336-1_2
8 2 Python Type Hints

This produces as output:


a_variable type = <class 'int'> = 42
a_variable type = <class 'float'> = 1.345
a_variable type = <class 'str'> = Hello
a_variable type = <class 'bool'> = True

Of course, as the above shows, a variable in Python can hold different types of
things at different types, hence the term dynamically typed.
As Python knows what types variables hold it can check at runtime that your
programs are valid/correct given the types involved for example in a particular oper-
ation. Thus, it is valid to add two integers together and indeed two strings together
(as this is string concatenation) but attempting to add an integer to a string will result
in a TypeError:
print(1 + 1)
print(1.2 + 3.4)
print("Hello" + "world")
print("Hello" + 1)

This code produced the following output including the TypeError:


2
4.6
Helloworld
Traceback (most recent call last):
File "/Users/jeh/temp/pythonProjects/course/main.py", line 15,
in <module>
print("Hello" + 1)
TypeError: can only concatenate str (not "int") to str

2.3 The Challenge for Python Developers

The challenge for Python developers comes when they need to understand what types
are required by, or work with, some API. As a very simple example, consider the
following function:
def add(x, y):
return x + y

What types can be used with this function?


In essence any type can be used for the parameter x that supports the plus operator
(+) with the type in y. From the above we know that integers and strings can be used,
but we can also use floating point numbers, for example:
print(add(1, 2))
print(add(1.2, 3.4))
2.4 Static Typing 9

print(add(1, 3.4))
print(add(5.5, 1))
print(add("Hi", "There"))

All of the above are valid parameters, and the output produced from the above
code is:
3
4.6
4.4
6.5
HiThere

Even custom types can be used if they implement the special __add__(self,
other) operator method, for example:
class Quantity:
def __init__(self, amount):
self.amount = amount

def __add__(self, other):


return Quantity(self.amount + other.amount)

def __str__(self):
return f"Quantity({self.amount})"

q1 = Quantity(5)
q2 = Quantity(4)
print(add(q1, q2))

The __add__() method allows the custom type (class) being defined to be used
with the add operator (‘+’). Thus this program generates the following output:
Quantity(9)

However, what was the intent of the designer of this add() function? What did
they expect you to add together? The only option in traditional Python code is for
the developer to provide some form of documentation, for example in the form of a
docstring:
def add(x, y):
"""adds two integers together and
returns the resulting integer."""
return x + y

2.4 Static Typing

Languages such as Java, C# and C are statically typed languages. That is when a
variable, object attribute, parameter or return type is defined then the type of that
element is specified statically a compile time.
10 2 Python Type Hints

Thus, an add() method on a Java class Calculator might be written as


follows:
package com.jjh;

public class Calculator {

public int add(int x, int y) {


return x + y;
}

This makes it clear to a Java programmer and to the Java compiler that the add()
method will only handle integers and will return as a result an integer type. Thus,
there is no possibility that a developer might try to add a number to a Boolean value,
etc. In fact the compiler will not even allow it!
The Java Calculator class can be used as shown below, note that this code
will not even compile if the developer tries to add two strings together. In this case
we are adding two integers together, so all is fine:
package com.jjh;

public class App {


public static void main( String[] args ) {
System.out.println( "Starting" );
Calculator calc = new Calculator();
System.out.println(calc.add(4, 5));
System.out.println("Done");
}
}

As the above program uses valid integer types with the add() method, the output
from the compiled and executed program is:
Starting
9
Done

2.5 Python Type Hints

Python’s Type Hints are more like a half-way house between traditional Python’s
lack of typing information at all and the very strict string static typing approach of
languages such as Java.
A Type Hint is additional type information that can be used with a function
definition to indicate what types parameters should be and what type is returned.
This is illustrated below:
def add(x: int, y: int) -> int:
2.6 Type Hint Layout 11

return x + y

In this case it makes it clear that both x and y should be of type int (integer
types) and the returned result will be an int. However, adding Type Hints as shown
above has no effect on the runtime execution of the program; they are only hints and
are not enforced by Python per se. For example, it is still possible to pass a string
into the add() function as far as Python is concerned.
However, static analysis tools (such as MyPy) can be applied to the code to check
for such misuse. Some editors, such as the widely used PyCharm, already have such
tools integrated into their code checking behaviour.
If you want to use a tool such as mypy instead, or in addition to that available in
your IDE, then you can install it using
pip install mypy

Or if you want to use conda/Anaconda by using


conda install mypy

You can now analyse your code by applying MyPy to a Python file, for example:
% mypy main.py
main.py:3: error: Incompatible types in assignment (expression has
type "float", variable has type "int")
main.py:5: error: Incompatible types in assignment (expression has
type "str", variable has type "int")
main.py:24: error: Argument 1 to "add" has incompatible type "str";
expected "int"
main.py:24: error: Argument 2 to "add" has incompatible type "str";
expected "int"
main.py:44: error: Argument 1 to "add" has incompatible type
"Quantity"; expected "int"
main.py:44: error: Argument 2 to "add" has incompatible type
"Quantity"; expected "int"
Found 6 errors in 1 file (checked 1 source file)

2.6 Type Hint Layout

The Python Style Guide defined by Python Enhancement Proposal 8 (PEP 8) provides
some guidance for using Type Hints, for example:
• Use normal rules for colons, that is, no space before and one space after a colon:
text: str.
• Use spaces around the = sign when combining an argument annotation with a
default value: align: bool = True.
• Use spaces around the -> arrow: def headline(…) -> str.
12 2 Python Type Hints

2.7 Type Hints for Multiple Types

Of course our add() function could work with floating point numbers as well as it
works with integers. It would therefore be useful to be able to state this in terms of the
Type Hints. Prior to Python 3.10 this could be done using a Union type, for example
Union[int, float] which while it worked was a little unwieldy. Since Python
3.10 we can use the style syntax bar ‘|’ for example int | float as shown below:
def add(x: int | float, y: int | float) -> int:
return x + y

2.8 The Self Type

Python 3.11 introduced the Self type which is defined in PEP 673. This can be used
to indicate that a method returns a reference to itself, for example:
from typing import Self

class Shape:

def __init__(self):
self.scale = 0.0

def set_scale(self, scale: float) -> Self:


self.scale = scale
return self

2.9 The Benefits of Type Hints

There are a range of benefits to using Type Hints in Python, for example:
• They help catch some errors within programs. Obviously, the biggest benefit
is that Type Hints can help developers catch certain types of problems in their
code (assuming that some form of type checker is used).
• They provide documentation. Type Hints can also act as a level of document
that editors such as IDEs can pick up and display to other developers.
• They can be work with IDEs. They can help with code generation and IDE
auto-complete functionality.
• They can make developers stop and think. They can help ensure that developers
think about their code and what types should be supported.
• They can improve understanding of libraries. Although Type Hints may offer
little advantage in a single use script, or throw away program, they can be of
significant benefit when a library is being created. Such libraries will be used
2.11 Online Resources 13

by a range of different developers, and some may be released into the wild, for
example via PyPI, the Python Package Index. The use of Type Hints can greatly
enhance others understanding of the APIs provided by these libraries.

2.10 Summary

If you are just starting out with Python, or you are writing scripts that will only be used
once, then Type Hints may not be particularly useful. However, if you are creating
libraries or developing larger more complex applications with teams of developers,
then they can be very useful indeed.

2.11 Online Resources

• https://docs.python.org/3.10/ Python 3.10 documentation.


• https://docs.python.org/3.11/ Python 3.11 documentation.
• https://en.wikipedia.org/wiki/Type_system Wikipedia Type System page.
• https://en.wikipedia.org/wiki/Dynamic_programming_language Dynamically
typed languages.
• https://docs.python.org/3/library/exceptions.html Exception handling in Python.
• https://www.pythontutorial.net/python-basics/python-type-hints/ Tutorial on
Python Type Hints.
• https://pypi.org/project/mypy/ MyPy static type hint analysis tool.
• https://mypy.readthedocs.io/en/stable/ MyPy documentation.
• https://www.jetbrains.com/pycharm/ PyCharm IDE tool.
• https://peps.python.org/pep-0008/ Python (PEP 8) Style Guide including guid-
ance of how to layout Type Hints.
• https://peps.python.org/pep-0673/ Information on the Self type.
• https://pypi.org/ The Python package Index PyPi.
Discovering Diverse Content Through
Random Scribd Documents
The Project Gutenberg eBook of Lappalaisia
lauluja
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Lappalaisia lauluja

Editor: Otto Donner

Release date: March 25, 2024 [eBook #73262]

Language: Finnish

Original publication: Helsinki: Suomalaisen Kirjallisuuden Seura, 1876

Credits: Jari Koivisto and Tapio Riikonen

*** START OF THE PROJECT GUTENBERG EBOOK LAPPALAISIA


LAULUJA ***
LAPPALAISIA LAULUJA

Kokoili

O. Donner

Helsingissä, Suomalaisen Kirjallisuuden Seuran kirjapainossa,


1876.

Omistettu Elias Lönnrot'ille suomalaisen


kansalaulun ansiorikkaalle herättäjälle.

Sisällys-luettelo:

Alkulause.
I. Varemmin julkaistuja Lappalaisia runoja. —
Fjellner. -Sorsele.
II. Lappalaisten kertoma-runot: Päiven paarne,
Piššan Paššan pardne, Päiven neita ja Kassa muödda.
III. Lapin runouden eri lajit: kertoma-runo, tarinoita
ja elinsatuja. -Sananlaskuja ja arvoituksia.
IV. Lyrillistä runoutta.
V. Runo-mitta.
VI. Ikä. — Laulujen muoto Syrjäniläisillä ja
Mordvalaisilla. — Yhteinen ja alkuperäinen
satu-aine. — Jumaluus-käsitykset.
VII. Kertoma-runot.
VIII. Pienempiä lauluja.

Alkulause (Elias Lönnrot'ille).

Tuo paimentolaisten puutoksista niin yltäkylläinen elämä


Lapinmaan härmäisillä takamailla ei suo heille paljon tilaisuutta
antautua runollisuuden onnellisempiin unelmiin; ankara taistelu
olemuksen puolesta antaa ajatuksille kokonaan niiden sisällön. Sen
vuoksi kuvastavatkin tässä jäljempänä seuraavat laulut, ainoat jotka
nykyiseen aikaan saakka ovat kootut, ainoastaan aivan vähän
kehittynyttä henkistä elämää. Kuitenkin on Sinusta, joka olet niin
perehtynyt suomalaisten kansalauluin kukkaistarhaan, halvalla
kanervallakin tuore metsätuokseensa. Ota se siis hyväntahtoisesti
vastaan.

Sinä tiedät kyllä ett'ei se vaadi itselleen suurta runollista arvoa.


Kansatieteellisenä kuvaelmana, osoitteena siitä, kuinka ihmisen
ajatustapa muodostuu niin puutteellisissa ja vaivanalaisissa suhteissa
lienee tällä kokouksella kuitenkin suomalaisten kansain
sivistyshistoriassa arvonsa. Sulimmat kiitokseni siitä harrastuksesta,
jota olet osoittanut tätä kohtaan, mutta erittäinkin "Päivän poikain"
suomen- noksest Sallittakoon minun tässä lausua kiitollisuuteni
niillekin, jotka tiedonannoillansa ja aikaisemmilla käännöksillänsä
ovat saattaneet tehtäväni mahdolliseksi. Rakkaassa muistossa on
vanha Fjellner Sorselessa säilyttänyt muistelmia lapsuudesta —
vuosisatamme alusta. Hänettä olisivat ne luultavasti jo aikoja sitten
haihtuneet kansan muistosta. Olkoot nämä vanhuksen mielestä
ikään kuin hänen oma pystyttämänsä muistopatsas esi-isille!

Useimpia lauluja antoi minun käytettäväkseni kuolinvuoteellansa,


nykyjään tuonen majoihin muuttanut, Jaakko Fellman Lappajärvellä,
toisia antoi minulle ystävällisesti J.U. Grönlund Tukholmassa.
Kääntäissä olivat erittäinkin herra pastori Joh. Mörtsell Maidissa ja A.
Laiti Vesijärvellä sekä J. Krohn ja A. Genetz täällä useimpain lauluin
suomentamalla ystävällisimmästi avulliset. Heille jokaiselle pyydän
lausuani sulimmat kiitokseni.

Laulunäytteet, joita on ko'ottu Venäjän Lapissa, saattavat


arvelemaan, että niitä on vielä melkoiset määrät lappalaisten kesken.
Onnistukoonpa vielä jonkun saada kootuksi sellaisiakin, 'joilla on
suurempi runollinen arvo ja tulkoon siten todistetuksi, että
lappalaisetkin kerran ovat olleet samanlaisten tunteiden elähyttämät
kuin heidän heimokansansa.

Helsingissä, tammikuussa 1876.

O. D.
I.

Varemmin julkaistuja lappalaisia runoja. — Fjellner'in elämäkerta. —


Sorsele.

Vaikka Lappalaiset ja heidän omituinen elämänsä Pohjani


lumitanterilla jo lähes kolme vuosisataa ovat olleet vilkkaiden
kertomusten esineenä, joita sekä oman maan miehet että
ulkomaalaiset ovat julkaisseet, niin on kuitenkin aivan luonnollisesti
tämän elämän ulkonaisempi puoli ollut muukalaisille viehättävin.
Tosin on tämän ohessa annettu myöskin jonkinlaisia tietoja kielestä
ja sen heimoista, mutta ensimäinen täydellinen kieli-oppi, jonka
toimitti P. Fiellström Etelä-Ruotsin murteesta, ilmestyi vasta 1738.
Vähän laveammalta ovat lähetyssaarnaajat ja muutamat matkustajat
kertoneet Lappalaisten pakanallisista jumaloista; täydellisen
kuvauksen heidän mytologiastaan antoi kuitenkin vasta v. 1871 J.A.
Friis, tuo Lapin kansan tuntemisessa ansiollinen Christianian
yliopiston professori, joka myöskin samassa kirjassa norjan-kielisenä
käännöksenä julkaisi suuren joukon lappalaisia satuja ja tarinoita
Lapin eri tienoilta. Siihen saakka oli tämmöisiä ilmestynyt paraasta
päästä satunnaisesti. Ensimäiset julkaistut lapinkieliset tuotteet,
jotka olivat lähteneet kansan omasta kuvaus-aistista, ovat Friis'in v.
1856 ulosantamat lappalaiset sadut ia tarinat, 41 luvultansa, jotka
hän julkaisi "kielen näytteinä".[1]

Tämä huolimattomuus ominaisesta, lapinkielisestä osoitteesta,


joka kuvaelisi kansan ajatustapaa ja mielenlaatua, on kuin jo 17
vuosisadan alusta pappien ja lähetyssaarnaajien tarpeeksi oli ruvettu
painattamaan lapinkielisiä kirjoja ja sentähden varmaankin, yksistään
kielen taidonkin vuoksi, myöskin omakielistä tekstiä olisi tarvittu.
Mutta kansalle omituisten tarinain arvo oli jotenkin alhaalle laskettu,
erittäinkin koska niitä julkaistiin enimmiten suorasanaisessa
muodossa. Vaan että myöskin runoja Lappalaisilla oli olemassa,
olivat jo useat kirjailijat väittäneet. Scheffer julkaisi arvokkaassa
kirjassansa Lapin maasta kaksi pientä laulua, sekä alkuperäisellä
kielellä että latinaisella käännöksellä, jotka tähän asti ovat olleet
ainoat lapin kielellä.[2] Sjögren kertoo,[3] että Sodankylän
Lappalaisilla on runoja, joissa lauletaan heidän esi-isiensä menneinä
aikoina loihtovoimalla toimittamia urostöitä, ja hän lausuu tässä
tilaisuudessa, että täydellinen semmoisten runojen kokoelma olisi
varsin tärkeä käsitykselle Pohjanmaiden pakanuuden omituisesta
luonteesta. Samassa Sodankylän pitäjässä kirjoitti hän muistoon,
monista muista puhumatta, myöskin yhden lappalaisen runon, joka
kertoi miten köyhä Wenäjänpuolinen Lappalainen kosi ruotsalaista
lappalaistyttöä naapuristossa (l.c. siv. 221). Mihin nämä runot ovat
joutuneet, sitä ei tiedetä; hänen jälkeen jättämissänsä papereissa
Pietarin akatemian kirjastossa niitä ei löydy, sen mukaan minkä
minulle hra valtioneuvos Wiedemann on suosiollisesti ilmoittanut.

Tämä viittaus lappalaisten kansanrunojen keräilemiseen ei näy


synnyttäneen uusia puuhia. Mutta v. 1849 ilmestyi ruotsalaisessa
aikakauskirjassa "Läsning för folket", vuosikerta XV ja seurr.,
jokseenkin hauskoja kertomuksia Ruotsin Lapista ja sen asukkaista,
jotka oli toimittanut ijäkäs, tätä nykyä jo yli 90 vuoden vanha,
pastori J.A. Linder Uumajalla, ja jo kirjoituksensa ensimäisessa
osassa (vuosik. XV, siv. 341 ja seurr.) ilmitoi hän ruotsalaisena
käännöksenä otteen lapin kielisestä Peiven parneh (auringon pojat)
nimisestä runosta; hän oli saanut tämän eräältä pastori Fjellner'iltä.
Tämä tällä tavoin julkaistu kertomaruno levisi päivälehtiin, (Postoch
Inrikes Tidningar Tukholmassa, Helsingfors Morgonblad N:o 84
vuosik. 1850, St. Petersburger Zeitung.) ja näistä toimitti sen W.
Schott saksalaisena käännöksenä A. Erman'in aikakauskirjaan "Archiv
für wissenschaftliche kunde von Russland" nid. XII ss. 54-61,
Berlinissä v. 1853. Moniin vuosikausiin tästä runosta, saatikka sitten
alkuperäisestä, ei kuulunut sanaakaan; se näytti joutuneen
unohduksiin. Friis sen uudestaan painatti mythologiaansa (J.A. Friis,
Lappisk Mythologi, eventyr og folkesagn. Christiania 1871, s. 169
seurr.) sen muodon mukaan, mikä runolla on lehdessä "Läsning för
folket"; sittemmin saatti sen taasen t:ri Bertram saksalaisen yleisön
luettavaksi (Peivash Parneh, Die Sonnensöhne. Nach bruchstücken
einer epischen Volkssage aus Lappland, von Dr Bertram. Helsingfors
1872.), ehkä kuitenkin muodossa, joka varsin vaillinaisesti kuvastaa
tuon lappalaisen runon alkuperäistä luonnetta ja suoraa esitystapaa.
Myöskin englantilainen käännös ilmestyi, nähtävästi sommiteltu
viimemainitusta saksalaisesta mukailemasta.(Peivash Parneh, the
sons of the Sun-god. Translated to English by Mr Weatherby,
Colburnin New Monthly'ssa. Katso aikakauskirjaa "Academy", 17
tammik. 1874, siv. 61.)

Perinpohjaisessa kuvauksessaan Lapin oloista: "Om Lappland och


Lapparne, företrädesvis de svenske. Ethno-grafiska studier af Gustaf
von Düben. Stockholm 1873", jota runsasvaraista kokoelma-teosta
varten on käytetty kaikki kirjoitukset, mitkä siihen saakka tästä
aineesta löytyi julkaistuna, omistaa kirjäntekijä kokonaisen luvun
sivv. 318-347 Lappalaisten runollisuudelle ja soitannolle. Aivan oikein
muistuttaa hän, että useimmat heidän tutkijansa ovat laiminlyöneet
tätä puolta heidän sivistyselämässään. Mutta tähän oli syynä se, että
asiasta ei paljon mitään tiedetty. V. Düben'in onnistui Sorselen
pastorin A. Fjellner'in suusanallisen kertomuksen mukaan, jota
miestä kirjoittajan "Läsning för folket" lehdessä tuli kiittää
ensimäisestä tiedosta Päiven parneh runosta, antaa täydellinen
käännös tuosta runosta, vieläpä myöskin ilmituoda ihan uusi
epillinen runo: Pišša Pašša'n poika, ynnä useain lyrillisten runojen,
mytillisten kertomusten ja eläintarujen kanssa. Yhden osan näistä sai
hän hra kauppaneuvos J.U. Grönlundilta Tukholmassa, joka on
syntyisin Lapista. Nämä runot ja laulut antoivat arvollisia ja tärkeitä
lisäkeinoja Lappalaisten henkisen kehityksen tuntemiseen.
Tarkoituksensa saavuttamiseksi -hän tahtoi saada aikaan
kansatieteellisen kertomuksen Lappalaisista -oli kirjantekijä kyllä
kylliksi tehnyt, sillä hän täytti tuon aukon heidän henkisen elämänsä
kertomuksessa. Saattaaksemme päätellä lappalaisen ja suomalaisen
kansanrunon synnystä oli kuitenkin välttämättömän tarpeellista, että
saatiin verrata alkuperäiset runot toinen toiseensa. v. Düben'istä
päättäin on pastori Fjellner ainoa koko Lapinmaassa, joka nyt enää
nämä runot tuntee. Mutta hän on jo -sanoo v. Düben -lähes 80
vuoden vanha ja sokea eikä sentähden pysty niitä enää kirjoittamaan
muistoon. Minä sentähden suvella 1874 päätin, tavatakseni hra
Fjellneriä, tehdä matkustuksen hänen luokse, kuljin Uumajan kautta
Lycksele'en ja täältä osittain jalkaisin osittain veneellä Sorsele'en,
missä tuo jo vuosien painosta vaipunut sokea laulaja asiaan
harrastuneena päivät pitkin minulle muistostaan luki useimmat näistä
runoista, jotka alempana olen alkuperäisessä muodossaan julkaissut.
Jo nuoruudessaan oli hän muiden muistista pannut joukon näistä
paperille; mutta suurin osa oli niin katkonaista ja aukkoista, että
sikäläisen murteen paras tuntijakaan ei olisi sitä ymmärtänyt.
Oikokirjoitus oli ylen mielivaltaista ja Säännötöntä, jotta usein
saimme hikoilla kauvan aikaa, ennenkun voin tavailla ilmiin oikean
sanan. Kaikki, mitä hänen suusanansa mukaan kirjoitin, panin
paperille tarkkaan niinkuin hän äänsi; en ole mitään yhtämukaisuutta
kokenut saada toimeen, lapin kirjakieltä Ruotsissa taikka muiden
puhumista vertaamalla. Viivyttyäni Sorselessa puolitoista viikkoa
matkustin Malå'n kautta Norsjö'hin 13 à 14 Ruotsin penikulmaa, ja
täältä kärryillä Skellefteå'hon.

Koska sen miehen elämäkerran tunteminen, joka jo monia vuosia


on ollut ainoa, millä vanhemmista runoista on jotakin tietoa, ei saata
olla vähäpätöistä, niin annan tässä hänestä muutamia tietoja, jotka
olen saanut osittain häneltä itseltään osittain v. Düben'istä.

Anders Fjellner syntyi syysyön kylmässä v. 1795 18 p. syyskuuta


taivasalla Rūta vuoriston lumitunturilla Votta ja Sāl vuorien välissä
Herjedal'issa, lähellä Ruijan rajaa, ja tuli kylmässä kaltiossa pestyksi;
paikkakunta on Heden pitäjää. Hänen vanhempansa olivat kiertäviä
poro-lappalaisia. Mutta kun isä jo vuonna 1804 kuoli, lähetti eräs
kaukaisempi sukulainen tuon vilkkaan nuorukaisen Östersund'in
kouluun Jämtlannissa. Sieltä tuli hän Hernösand'in lukioon, jonka
lukujaksot suoritettuaan hän harjoitti lukemista Upsalan yliopistossa
v. 1818. Jo koulussa oli hän omaksunut nimen Fjellner siitä syystä,
että hän oli syntynyt korkealla vuorella (fjäll), samate kuin muutkin
nuorukaiset lappalaista syntyperää olivat omaksuneet fjäll-sanasta
johtuneita nimiä: Fjellström, Fjellman. Luku-vuotensa kaikki lupa-ajat
vietti hän kotiseuduillaan sukulaisten luona, pitäen täyttä
paimentolaiselämää. Täällä kuuli hän usein vanhojen ihmisten pitkinä
iltapuhteina muistostaan lukevan muinoisia runoja ja kertovan satuja
sekä tarinoita, taikka tuotiin tunteet ilmiin ilavissa lauluissa,
vuole'issa, jotka sanoin sävelin kuvastivat mitä erilaatuisimpia mielen
toiveita ja taipumuksia. Näitä vuole'ita laulettiin tavallisesti
ainoastaan taivasalla. Paraim-pien laulajain joukosta muisti fjellner
vielä erään Serri Jū'n, Anders Nilssonin, Per Mihte'n ja Ruijan puolella
Sakari Olavin-pojan vaimon, Kant ja Stolt nimisestä suvusta. Liike
Ruijan ja Ruotsin välillä oli, näet, näillä rajatienoilla varsin vilkas,
erittäinkin vaelsivat Lappalaiset usein edes takaisin; kertomaja
laulutaito oli heissä kaikkialla yleinen.

Vuonna 1820 jätti fjellner yliopiston ja vietti nyt


lähetyssaarnaajana monta vuotta Pohjois-Ruotsin Lappalaisten
kesken, kuluttaen suurimman osan aikaa matkoihin. Niin tapaamme
hänet v. 1821 apulaisena tuolla Lapin oloihin perehtyneellä pastori L.
L. Læstadius'ella Karesuannossa, joka on Ruotsin Lapin pohjoisimpia
pitäjiä. Vuodesta 1828 vietti hän apulaisena jonkun ajan
Jukkasjärvellä, missä hän sitten yhtä mittaa oli asuntoa vv. 1831-
1842. Viimemainittuna vuonna muutti hän, vaimo, kaksi lasta ja 11
peuraa parissansa, ihan samalla tapaa kuin Lappalaiset talvisaikana
asuinpaikkojansa vaihtavat, Sorsele'en, missä hän siitä lähtien on
pappina oleskellut.

Tämä Sorselen pitäjä on Westerbottnin Lappia, jonka ala on 364


neliöpenikulmaa ja asukasluku 18,495 henkeä. Suurin osa näitä tosin
asuu rantamailla, mutta miten ruotsalainen asutus vireästi entää
edespäin, samalla kun lappalainen väestö joko vähentyy taikka pysyy
entisillään, on huomattava siitä, että väkiluku samojen rajojen sisällä
v. 1789 nousi ainoastaan 1,027 henkeen, joista suurin osa
Lappalaisia. Mutta yllämainituista 18,495 asukkaasta v. 1873 oli
ainoastaan 1,147 Lappalaisia, ja näistä tuli Sorselen pitäjän osalle
ainoastaan 267 Lappalaista 1,331 Ruotsalaista vastaan; P.
Læstadius'en mukaan (journ. II, 435) oli v. 1790 Sorselen
Lappalaisten luku 323 ja v. 1832 360. Miten tämän maan alan viljelys
80 vuotena on edistynyt, nähdään siitä, että veroitetun maan arvo v.
1790 laskettiin 49 ¼ manttaliksi, mutta v. 1873 jo 225 %
manttaliksi. Vaan mitä enämmin viljelys voittaa alaa, mitä enämmin
ruotsalaiset uutisasukkaat leviävät pohjoseen ja Norjan rajalle päin,
sitä varmemmin katoavat myöskin vähitellen Lappalaiset. Lapset
oppivat jo tähän aikaan suurimmaksi osaksi ruotsia ja sulavat siten
ruotsalaiseen väestöön, ihan samoin kuin Wermlannin Suomalaiset,
mitä kieleen tulee, nyt enää ainoastaan korpiensa kaukaisimmissa
perukoissa käyttävät äidinkieltään. Eikä saattane enää kestää
enämmin kuin vuosisadan taikka korkeintaan kaksi, ennenkun Lapin
kansa Ruotsissa, parannettujen kulkuneuvojen ja oppilaitosten
vaikutuksesta, on täydelleen sulanut Ruotsalaisiin.
II.

Lappalaisten kertoma-runot: Päiven paarne. — Piššan Paššan


pardne. —
Päiven neita. — Kassa muödda.

Ennenkun v. Düben arvokkaassa teoksessaan Lappalaisista


käännöksinä julkaisi nuo lukuisat runot, ei tiedetty mitään semmoista
runomittaisessa muodossa, paitsi tuo yllämainittu runo Päiven parne.
Hän julkaisi nyt kirjassaan, kuten jo ylempänä sanottiin, Fjellner'in
käännöstä noudattaen, sekä tämän runon että myöskin tuon yllä
mainitun Pišša Pašša'n pojasta, vieläpä kolmannenkin: Peijen neida,
päivän tytär, jonka suurin osa kuitenkin on suorasanaisessa
muodossa. N.s. Stalu-saduista löytyy hänen teoksessaan
runomittainen Kassa muodda, vahva turkki, ja muutamia
suorasanaisia, eläintäni lohesta ja taimenesta, joitakuita uudempia
runoja sekä lyhykäisiä epigrammatillisia pätkiä. Näistä tahdomme,
kustakin erikseen, laveammalta puhua.

Tuon epillisen runoelman Päiven pārne päivän pojat, jonka entiset


julkaistukset ylempänä olemme ottaneet huomioon, on v. Düben
kokonaisuudessaan ilmituonut seuraavalla uudella nimityksellä:
Peivebarnen suongah jehtanasain maajisn, päivän pojan kosiomatkat
jättiläisten maassa. Tätä verrattaessa ennen julkaistuihin teksteihin
huomaa, että pääasiallinen sisällys on sama; v. Düben on vaan
antanut runolle, niinkuin sillä alkukielessäkin on, metrillisen muodon;
myöskään ei löytynyt ennen alkuvärsyjä. Fjellner'in aikaisemmin
antaman tiedon mukaan on runo korjattu paperille Tornion Lapissa
(Jukkasjärvellä) Leuhnje niinisen Lappalaisen suusanan mukaan.
Minulle kertoi hän, että runoa on laulettu sekä Jukkasjärvellä että
Herjedal'issa, missä viimeinmainitussa paikkakunnassa nuo jo
mainitut Serri Jū ja Sakari Olavinpojan vaimo sen olivat osanneet.[4]
Viittä viimeistä riviä arvelee hän myöhemmäksi lisäykseksi, minkä
myöskin näkyy todistavan Linder'in väite, että niitä tunnettiin
ainoastaan Tornion Lapissa.

Minun alempana julkaisemani teksti on Fjellner'in lausunnosta


tarkasti kirjoitettu hänen äänteensä mukaan. Minulla oli tässä
edessäni myöskin toinen kopio, minkä hän monia vuosia sitten itse
oli kirjoittanut; muutamat toisinnot ovat lähteneet tästä lähteestä
taikka syntyneet hänen muistutuksestaan: on myöskin näin laulettu.
G. kirjaimella merkityt olen saanut eräästä käsikirjoituksesta, minkä
kauppaneuvos J.U. Grönlund Tukholmassa hyväntahtoisesti
käytettäväkseni antoi. Myös senkin tallensi Fjellner 40
vuosikymmenen alussa paperille, pehmeämmällä etelä-murteella
kirjoitettuna; siinä seurataan, kuten edellisissäkin norjalais-
ruotsalaista oikokirjoitusta, missä etenkin vokali-ääntiöt varsin
vaillinaisesti kuvautuvat.

Tämän runon sankari on Kallajälkeinen; hän ja koko hänen


sukunsa ovat syntyperää auringon tyttärestä. He keksivät sukset, he
ajoivat ja kesyttivät peuroja, joita löytyy Cassiopæa'ssa, ja
ylimalkaan on kaikki mitä heidän elämäänsä kuuluu likimmäisessä
yhteydessä taivaallisten kohtain kanssa. Jupiter'inä on tuo loistava
peura, Venus'ena karvan-vaihtava naaraspeura, kiertotähtinä ovat
ylimalkain nuoret koiraspeurat, joita kiiman aikana on ajettu erilleen
karjalaumasta. Otava on heidän kaarensa, seitsentähti on Kalla-
poikain njalla'na, aittana.[5] Itse ovat he myöskin tähtiä: Orion on
yksi, Sirius on Kalla pardne, ja monet muut, niinkuin āks kuč, käls
kuč, kums kuč, jumpik ovat Päive pārne'ita, auringon-poikia. Mitä
kalla nimeen tulee, muistuttaa Schott, että se oikeastaan merkitsee
ijästynyttä taikka nainutta miestä, mutta että se ehkä on jossakin
yhteydessä suomalaisen Kaleva nimen kanssa; tässä kohden olisi
etenkin muistaminen, että Suomalaiset nimittävät Orion tähteä
Kalevan miekka.[6]

Toinen epillinen runo on Piššan Paššan pardne, Pišša Paššan poika.


Ensimäisistä rivistä käy selväksi, että isän nimi oli Pišša, äidin Pašša,
mutta runon joutuessa saapi kuitenkin isä molemmat nämä nimet.
Runo on sangen omituinen. v. Düben siitä sanoo: Koko Runosta
käypi selvä lappalainen henki. Aatteet ovat, jos luetaan pois Noidan
pitkä puhe, umpilappalaiset; samote myös tapausten kohdat. Ne
paikat, missä kaksintaistelut, taistelu-apulaiset ja haudankaivajat
sekä noidan tappeluksen vaatijana astuvat esiin, ovat ihan uusia ja
vieraita; mitään siihen vastavaa en ole missäkään tavannut.[7]
Epäilemättä on runo vallan vanha, jos ei sitä, niinkuin Fjellner tekee,
juuri johdattaisikaan Lappalaisten alkukodista Aasiassa. Jo tästäkin
syystä on mielestäni v. Düben aivan oikeassa, kun hän v. 54 kääntää
sanat varrek ja krappuk kannuskenkä ja kinnas sanoilla, sillä näillä
on yksinään tämä merkitys eivätkä ne ensinkään tiedä mitään
raudasta; kypärä sanaa on hän paremman puutteessa käyttänyt.
Säejaksoissa 83 ja 124 on hän kuitenkin säilyttänyt rautapantsari
sanan, se kun näet on tärkeä, koska sankari sen painaa vihollisen
rintaan, ja se siitä syystä myöskin arvattavasti oli rautainen.
Muistuttaminen on kuitenkin, että yhdessä toisinnossa molemmissa
paikaissa rauta sanan sijassa on sōte sarkab, mikä merkitsee
ainoastaan sotapaitaa.

Runon sisällys, jonka v. Düben käännöksessä kehittää, pitää


jotenkin tarkasti yhtä erään alkumuodon kanssa, joka vielä on
Fjellner'in omassa hallussa ja jonka hän moniaita vuosia sitten
kirjoitettavaksi luki silloiselle apulaiselleen, nykyiselle Malån
kirkkoherralle Juhana Mörtsell'ille. Sanat, jotka hän minulle mennä
kesänä kirjoitettavaksi luki ja jotka alempana olen julkaissut,
poikkeevat ainoastaan erityisissä lauseissa ja varsin vähäpätöisestä
ensinmainitusta, niinkuin muistutuksista on nähtävänä.
Paluumatkallani Sorselesta viivyin kaksi päivää Malå'ssa, missä olin
tilaisuudessa hra Mörtsell'in kanssa tarkastella P.P. runon alusta
loppuun, jolloin hän ystävällisesti antoi minulle monta hyödyllistä ja
valaisevaa selitystä. Tämä runon muoto on Fjellner'in mukaan
kotoisin Pohjois-Lapista, mutta toisen paljon lyhyemmän on hän jo
nuorena ollessaan kirjoittanut Herjedal'issa Tämä löytyikin hänen
papereistaan nimellä Piššan Paššan alge, P.P:n poika. Pahaksi
onneksi oli kuitenkin tämä toisinto kirjoitettu niin huonolla käsi-alalla'
ja oikokirjoituksen puolesta niin mielivaltaisesti, että siitä ei enää
voinut saada il-miin mitään järjellistä sisältöä; Mörtsellkin, vaikka hän
on hyvin tutustunut Ruotsin Lapin kieleen, sai mukaan ottamastani
kopiosta ainoastaan paikoittain selvää. Otan siitä seuraavat
pääkohdat: Miehen kuoltua, pakenee hänen vaimonsa metsältä
metsään (vulga batera tzemem tzememest). Viimein saapi hän
pojan, joka, suureksi kasvaneena, kysyy äidiltään: etnem, gokte mu
atijen njemme, äiti, mikä on isäni nimi? Vastaukseen, ett'ei hänellä
ole nimeä ensinkään, lausuu hän: imen lem monno muoriste
gedkiste tjettjelem (varmaankin čuočelam), enhän toki ole syntynyt
puista ja kivistä. Kun äitinsä hänen pyynnöstään (etnem, daita
mennen laipem) on leiponut hänelle leivän, pakoittaa hän hänet,
puristaen leipää käteensä: etnem, sardna mu atjen nimmem[8] äiti,
sano minulle isän nimi. Nyt saapi hän tietää syntyperänsä ja että
mustan vuoren harjanteen (tjebpes asen) Stalu on hänen isänsä
tappanut, mutta, jatkaa äiti: alle me pardnem dohka vuelke, älä
mene sinne, poikani. Hän menee kuitenkin ja astuu sisään
Hasman'in (?) kotaan: Hasmannen kåtan tjanga. Stalu käskee
palvelijansa kutsua vieraan luoksensa; nuorukainen tulee ja tapaa
vanhuksen leikkaamassa omistusmerkkiä peuran korviin. He
tervehtivät toinen toistansa, ja vanhus, turhaan koettaen osata
nuorukaista nuolillaan, antaa nuoren sankarin kysymyksiin nuo
täydellisemmästä runosta tunnetut vastaukset (Piššan Paššan
banine!). Tähän loppuu käsikirjoitus muutamilla sanoilla, joista ei saa
selvää. Tärkein kohta tässä katkelmassa on se, ett'ei noita muka
Aasiasta muistuttavia paikan nimiä (Altait, Baikkala peeliit, Lääna,
Ammart ja Čukčan oive) mainita sanallakaan, sekä myöskin, että tuo
uhkea tappelukseen vaatimus noidan kautta, taistelu-apulaiset ja
haudankaivajat jäävät pois; ja vieläkin, tuo pitemmässä runossa
tavattava noidan ylen pitkä, kristillisillä lauseilla koristettu, puhe
puuttuu kokonaan. Jos kohta v. Düben'in kanssa myöntää, että tuo
kohtaus miekkaisille vaatimuksessä on selvin lappalainen ja varsin
hyvin soveltuu runon sisältään yleensä, näkyy kuitenkin tämä toinen
toisinto todistavan, että muut osat s.o. nuo epäiltävät nimet ja
mainittu, pitkä puhe, ovat pidettävät myöhempinä lisäyksinä.
Johtopäätös joko tehdään tämä, taikka on otaksuminen, että runo
aikaisemmin on sisältönsä puolesta ollut mytillisempi ja sitten
vähitellen muodostunut semmoiseksi kuin se nyt on. Asianomaiset
välirunot ovatkin hyvin höllässä yhteydessä muun sisällön kanssa.
Nämä muistutukset koskevat myöskin 64 v. löytyviä säejaksoja
Huureskuče'sta ja llma-račče'sta; ne hääritsevät varsin tuntuvasti
kertomuksen juoksua ja puuttuvat: Herjedal'ista saadussa
käsikirjoituksessa. Tämä katkelma kun on erinomattain tärkeä tätä
miellyttävää runoa arvosteltaessa, liitän sen tähän
kokonaisuudessaan, kirjaimesta kirjaimeen semmoisena kuin se
Fjellner'in käsikirjoituksessa löytyy; sulkumerkissä liitän siihen
muutamia arveluita.

P.P. alge.

Stalo P.P. alge luotem ja itz dem nielem kojneb vuositze vulga
batera tzemem tzememest. Algem fihkije dej ne fontere. Gosse Stora
sjadta. Olle mosme gosse ge don tsepesse osonn valze olla. Njorte
dueikte manninne tetzelle. Aktelzem gåtan pucklelle fjerte (virttī)
smavelle. Vuejna ferte adnae. Ahtjem, etnem åtnei. A. etnemse
gihchie: Etnem gokte mu Atjen njemme? E. I ma namme do mige.
Ahtjet. Imen lem monno muoriste gedkiste tjettjelem (čuočelam). E.
Arme krovehkem gelijem possju raikem pekta kalkem sardnet. Maje
tjaka ge ficke goltte. Arme Momse (ruömse) kalles pjelje rohtziste
moriten verdet possja njalman votatella. Dille ahtzette njemmem
påtah kolenne. Dem vojte nimte siekta meitten. I dilloge sardnh.
A.E. Daita monnen lajpem. Etnebbe dojte. Rivest dem vuoss kerdam
pueke gessa tjoppam monnen! monne itz pessam. Dem fihkje.
Etnebben ketem beksa ketem dejne gekke lajpine djen taesti Etnem
sardna mu atjen nimmem. E. Hauh. P.P. mana mo. A.E. ff. Gop. pah
le siett. E. Tjehpes Asen. Stalo le ålge luotem. Alle me pardnem
dohka vuelke. Elge Ednisse ketem tuoj ta tellah tåhka tjolije.
Hasmannen kåtan tjanga. H. Tälla Pardne Ih den diste påte puosta
geje rajkemb knömme jokte kuossje påte tjetem. Itsim Ajiesse
sardneje. A. Vattsidde vatsidde pejkatetidde (piikutete, lasset
wissen). Sij vatse. St. Vattsidde kattsidde (koččute, rufet) kuössem.
Mo kajk. Dah kotsia sodne vadllde. A. Puorek Ajia. St. Buörest.
Todne Ajietsje toh (todn) Nuppen siten åjve. A. Jabette Aja. Stalo
stuöre sjeram tsiekkija (cehkije). St. Vatse Aijetse Pissema, tjöppeh
kjietebbem koh Itse. Pahtse olgesse tjettjelle (čuočele). Stalon verje
kudnedde. A. Aja manne dahkesn datte donjole noolemme. St Pissan
Pn banine. A. Aja masne date do spakkak njölem. P P buoenihe. A.
Aja kosne dat Do kurtek noolem. St. Mam lä pist dat äpa dam
monnom telpemene. Voji P P ålge kokka kalken tsettselit U vuo — —

*****

Viimeinen epillinen runo, joka on luettavana v. Düben'in teoksessa,


on oikeastaan sarja pienempiä satuja (Fjellner arvelee useampia
satoja), sisältönsä puolesta vertauksellisia ja mytillisiä, jotka
koskevat päivän tytärtä ja kertovat hänen elämäkertaansa, hänen
töitänsä ja kaikenlaisia siihen kuuluvia kohtia. Tähän kuuluu myöskin
satu Lappalaisten vaelluksesta etelämmistä maisemista Pohjaan.
Suurin osa näitä satuja näkyy ilmitulleen runollisesti toimitellulla
suorasanaisella muodolla, jolla ei vielä ole runomitan tarkasti
määriteltyjä jäseniä. Toisinaan muuttuu kertomus vähitellen neljälle
trokeelle perustettuun runomittaan. Pahaksi onnekseni en saanut
tästä laveasta runosta muuta kuin katkelman Fjellner'in lausumuksen
mukaan; hän näkyi kovasta työstä pian liian väsyneeksi voidaksensa
kohdastaan luetella minulle enempää; useampia viikkoja minä
taasen en voinut siellä viipyä. Tämä runo nimitetään Päive neita ja
kuvaa tuota, yli suurimman osan Lapinmaata levinnyttä, luuloa, että
muka se, joka voi saada auringon tyttären haltuunsa, siten myöskin
saapi hänen peurakarjansa ja rikkautensa. Fjellner itse luuli kerran,
samotessaan Herjedalin vuoriston poikki, hänet nähneensä. Ilma oli
käynyt sumuun. Yhtäkkiä kuuli hän karjakellojen soivan ja näki tuon
arvossa pidetyn neidon istuvan kiven päällä. Hän kiipi hänen
taakseen likistääksensa häntä syliinsä -hän halaili kiveä, johonka hän
löi päänsä, ja kaikki oli kadonnut! Minä mainitsen tämän näyt-
tääkseni perittyjen taikojen valtaa Lappalaisten mielikuvituksessa;
vaikka kerrottu ilmiö tapahtui hänen nuoruudessaan, olihan kertoja
kuitenkin mies, joka vuosikaudet oli nauttinut koulusivistystä.
Auringon tytöillä nimitetään myöskin toisinaan saivo neida, manalan
tytär, taikka raana, ruona neida vihertävä, s.o. kevään tytär, joka
antaa vuorille viheriän puvun.

Saduntapaisiin tarinoihin vivahtava, taikka oikeastaan niihin jo


kuuluvakin, on runomitan muotoon pukeunut kassa muodda, vahva
turkki. v. Düben'in antama toisinto on Tornion Lapista; itse olen
Sorselessa kuullut kaksi eri toisintoa samasta sadusta, ainakin osaksi
runomittaisia. Toisen kertoi 25 vuotias palvelustyttö Anna Sara, joka,
syntynyt lappalaisista vanhemmista, oli Sorselen isäntäni
palveluksessa. Toisessa sanoopi nuorempi poika, nähdessään
lappalaisen katsovan ympärilleen: ahčam, ahčam, čalme jollaret (=
jorralet), isä, isä, silmä liikkuu[9] Tämä tarina näkyy olevan
levinneenä yli koko Lapinmaan. Fjellner'in tiedonannon mukaan
sanottiin sitä Herjedal'issa kissa muodda'ksi, mitä muotoa myöskin
Sorselessa käytettiin. Linder julkaisee kertomuksen "Läsning för
folket" nimisessa aikakauskirjassa XV, 3 siv. 213, ja Friis antaa L. L.
Laestadius'en mukaan kirjassaan "Lappiske eventyr og folkesagn"
siv. 78-81 vasta mainitusta varsin vähän eroavan toisinnon nimellä
Patto poadnje. Myöskin 75 vuotias Nils Jansson, joka enemmän kuin
50 vuotta takaperin ensimäisenä uutisasukkaana tuli Soks-jaur'iin ja
oleskeli ahkeraa lappalaisten parissa, minulle saman jutun kertoi;
tämä oli myöskin tunnettu Arjeplog'issa, kuten Mörtsell minulle
ilmaisi.
III.

Lapin runouden lajit: epillistä runoutta, satuja ja eläintaruja. —


Sananlaskuja ja arvoituksia.

Friis, joka tuntee umpilappalaisia satuja ja taruja ainoastaan


suorasanaisessa muodossa, jakaa ne sisällän puolesta kolmeen lajiin:

Ensimäinen liikkuu mytillisissä olennoissa taikka sisältää


muistelmia lappalaisten vanhasta jumaluusopista, sadun muotoon
puettuina.

Toinen laji perustuu historiallisiin tapauksiin ja kertoo otteluista


vihollisten kansojen kanssa entisyydessä.

Kolmas puhuu eläinten omituisuuksista ja eri mielenlaaduista,


antaa kansallisia selityksiä heidän ulkonäöstään, väristään j.n.e.[10]

Saduista ovat, kuten Friis muistuttaa, useat nyky aikaisia ja


vieraita, lainattuja ympäri asuvilta Suomalaisilta, Ruotsalaisilta ja
Norjalaisilta. Näihin kuuluvat epäilemättä ne lukuiset jutut, jotka
puhuvat kuninkaista, ruhtinaista ja ruhtinattarista, linnoista j.n.e.
Toisinaan tapaapi kuitenkin myös näitäkin nimiä vanhemmissa
taruissa.

Muutamilla lisäyksillä saattaa tämä Lapin runouden jako yleensä


vieläkin pitää paikkansa epos-lajin suhteen. Ensimäiseen osastoon,
mytilliseen epos'een kuuluu etupäässä Päiven pärne ja kertomukset
Päiven neida'sta, ehkäpä myöskin erinäisiä kohtia Piššan Paššan
pardne'sta, mikä kuitenkin on enemmän historiallista luonnetta.
Stalu-sadut kuuluvat kyllä niinikään ensimaiseen jaksoon, etenkin ne,
joissa puhutaan Saivö'sta, Haššis-ädne'stä ja Njavvis-ädne'stä j.n.e.
Useimmiten kuitenkin ovat perin saduntapaiset seikkailukset
kertomuksen aineena, ja nämä eroavat korkeammasta mytillisestä
käsitteestä samaten kuin senkaltaiset sadut muissa kansoissakin.
Mutta tuo vähitellen ilmestyvä prosallinen käsite näyttäikse tässäkin,
esim. jos vertaa tuon puhdasrunolsen Njavvisene sadun Düben'issä
siv. 331-334 sitä vastaavaan Friis'issä, Sprogprøver siv. 81-83 ja 87-
89, Eventyr siv. 14-23. Toisen vielä mitättömämmän toisinnon
samasta sadusta kuulin kerrottavan Sorsele'ssa; molempien äitein
nimetkin oli siinä, unohdettu, puhuttiin ainoastaan Stalu'sta. Tätä,
joka pää-asiassa on samaa kuin jättiläiset (jättenes, jähtanas,
jätanas) kerrotaan kömpelöksi, ihmissyövaksi mieheksi, lappalaisia
suuremmaksi. Toisinaan silmäpuoli tai sokea; hän asuu etäällä
erillään muista ja on usein rikkirikas. Mutta hän kun on typerä,
heikommat Lappalaiset hänet usein pettävät. Hänen vaimonsa nimi
on Ludač, Luhdač (lude), jolla on tuon elävän muoto ja joka tavasta
käypi sokeaksi siten, että hän kätkee silmänsä kynnyksen alle.
Vihollisensa tappaa Ludač rautaisella putkella, jonka läpi hän imee
vihollisensa veren.[11] Friis johtaa nimen Stalu ruotsalaisesta
sanasta stål, teräs, joka ennen äännettiin myöskin stal, ja pitää sitä
seikkaa, että hän joskus on puettuna rautaiseen takkiin, todistuksena
siitä, että hän alkuansa merkitsi viking. Kuinka oikea tämä
etymologia on, lienee paha päättää.

Useat kirjoittajat ovat Stalu-satuja julkaisseet, niinkuin Högström,


[12] Laestadius,[13] Friis kielinäytteissään ja satukokoelmassaan siv.
73-110, sekä myöskin hänen mukaansa v. Düben. Sorsele'ssa olen
itse useampia kuullut, osittain Fjellner'ilta, osittain muilta; tavallisesti
pitivät ne yhtä ennen julkaistujen kanssa. Semmoisia tavataan
yltympäri koko Lapinmaan.

Historialliseen jaksoon kuuluvat kaikki ne sadut, joissa taistelut


naapurikansoja vastaan kerrotaan. Nämä ovat tavallisesti Tschudejä,
joita enimmiten ja erittäin pohjoisessa Lapissa pidetään karjalaisina.
Etelän puoleen merkitsee tämä nimitys ensimäisiä Lappalaisiin
tunkeuvia Ruotsalaisia, niin ainakin Sorsele'ssa, missä heidän
nimensä äännetään čure =čuude; sana merkitsee nyt ainoastaan
vihollista. Myöskin Venäläiset saavat tavasta tämän nimityksen,
vaikka kyllä tavallisia Karjelah, Ruošša-čudeh nimiäkin käytetään.
Tämänkaltaisissa tarinoissa ei ole vaihtelevaisuutta paljon. Etenkin
pohjasessa näytetään kaikkialla paikkoja, missä viekkaammat
Lappalaiset ovat syösseet vihollisen, joko kohisevaan koskeen taikka
syvään vuoren rotkoon, taikkapa jätetään tämä yksinäiselle saarelle,
missä hän koko joukkonensa kuolee nälkään tai muutoin
kaikellaisten konnankoukkujen kautta heittää henkensä.
Högström[14] ja Laestadius,[15] niinkuin myöskin Friis[16] ja muut
julkaisevat koko joukon semmoisia satuja, Aslak Laiti on kertonut
minulle moisia Utsjoen tienoilta.

Kolmas laji on tuo Lappalaiselle erittäin rakas eläin-taru, joka


häntä usein aika lailla huvittaa. Friis'in kokoelmassa on kolme
semmoista: kettu ja karhu, lohi ja ahven, metsäja koti-eläimet.[17]
Niitä on kuitenkin paljon enemmän, ihan kuin suomalaisilla. Niistä
lyhyemmistä lauluista, jotka alempana julkaisen, ovat muutamat tätä
läjiä, usein, kuten v. Düben muistuttaa, epigrammatillisesti teräviä ja
supistuneita. Mainittavat ovat vielä sananlaskut (sadne-vajasak) ja
arvoitukset (arvadusak), nämä näytteet kansan terävästä
havaintovoimasta, joita niin kosolta on Suomalaisilla ja Virolaisilla.
Friis on ottanut muutamia kielinäytteiden joukkoon; painatan ne
uudestaan tähän, koska kokoelma on, ensimäinen tähän saakka
tunnettu; ja hänen kirjansa ei ole helposti saatavissa. Kielimurre on
Finmarkin tai norja-laislappalainen.

Sadnevajasak, Sananlaskuja.

1. Adde bädnagi ja gula baha sanid. -Anna koiralle ja kuule pahoja


sanoja.

2. Buöreb lä čagar giedast, go buojde mäcest. -Parempi nahka,


(laiha puoli) kädessä, kuin rasva metsässä.

3. Buöreb lä bitta njalmest, go havve oajvest. -Parempi naarma


suussa, kuin haava päässä.

4. Buöreb lä jode, go oro. -Parempi mennä, kuin jäädä.

5. Dam olbmast läk ämbo juonak go suonak. -Tällä ihmisellä on,


enemmän juonia kuin suonia.

6. Dat, gäst gukkek läk dolgek, allagassi girda. -Jolla on pitkät


siivet, hän korkealle lentää.
7. Galle gaddest visaj, go avest vahag šadda. -Kyllä maalla viisaita,
kun merellä vahinko tapahtuu.

8. Garranasa bäsest matta gavdnujuvvut majda njufčamonne. -


Kaarneen pesässä saattaa olla joutsenenkin munia.

9. Go čiegnalis lä čacce, de lä rukkas bodne. -Jos vesi on syvää,


niin on pohja mutainen.

10. Havske guojbme oaned matke. -Hauska kumppani lyhentää


matkan.

11. I goarpa goarpa čalmi čuokko, -Toinen varis ei kaiva toisen


silmiä.

12. I läk jakke jage viellja. -Toinen vuosi ei ole toisen veli.

13. I šat häppad niära gaske. -Ei häpeä enää poskiansa pure.

14. I šat oarre-gaƷza galloi baste. -Oravan otsaa ei enää hänen


kyntensä syö. (Hän on haltioissaan ilosta taikka surusta).

15. I bäjve nu gukke, atte igja iboade. -Ei päivää niin pitkää, ett'ei
yötä tule.

16. Ik galga čalmetës gavpe dakkat. -Hän ei tee silmätöntä


kauppaa.

17. Loge visasa äi nakaš sanigujm ovta jalla SabmelaƷain. -


Kymmenen viisasta ei sanoissa pidä paikkaansa yhtä hullua
lappalaista vastaan.

18. Oapes bahha lä buöreb, go âmâs buörre. -Paha ystävä on


parempi kuin hyvä vieras.
19. Ovče visasa äi buvte buoddot ovta jalla. -Yhdeksän viisasta ei
osaa hullulta suun tukkia.

20. Äi läk buok vielljakj ovta ädne čiƷid njammam. -Ei kaikki veljet
ole yhden äitin rinnasta imeneet.

Arvadusak, Arvoituksia.

1. Aleb go buok varek ja vuöllegeb go dagnasak? Balgës. -


Korkeampi kuin kaikki vaarat ja matalampi kuin kanerva? Polku.

2. Alo vagjol ja ucca noadaš sälgest, mutto i vajbagoassege?


Dorte. -Aina se käypi, takka selässä, mutta ei väsy? Rukki.

3. Audal go ačče lä bälledagos, de lä bardne vuovdest? Suovva. -


Ennenkun isä on puoli-valmiina, on poika metsässä? Savu.

4. Bäjve giddagasast, ikko luovos? Juölge-suormak. -Päivin


vankeudessa, öisin vapaana? Varpaat.

5. Färra ija bäjve, mutto i oaƷo goassege smakko? Dimo, boccu


bjällo. -Hakkaa yöt päivät, mutta ei kuitenkaan saa lastua? Kello,
poronkello.

6. Gavvot guoros, gobmot dievva? Gapper. -Ylöspäin käännettynä


tyhjä; alaspäin täynnä? Lakki.

7. Gi lä buok visasamus majlmest? Bismar. -Kuka on kaikkein


viisahin maailmassa? Puntari.
8. Gierrag ald čuƷzo ja madda bajas od. gierra vuöllen, madda
bagjen. Gussasäjbe. -Se seisoo latvallaan juuret ylöspäin, tai latva
alaspäin, juuret ylöspäin. Lehmänhäntä.

9. Gädge-juölge, arpo-ärtegak ja muorra-oajve? Nuötte. -Jalat


kivestä, kupeet langasta ja pää puusta. Verkko.

10. Jabme gässa ellid vuovdest? Čokko. -Kuollut vetää eläviä


metsästä? Kampa.

11. Jomfruva čokka aja gaddest ja lukka oajvest (od. luodko


oajve)? Botka. -Neito istuu lähteen reunalla hattu päässä? Angelica
(puhkeematon).

12. Lokketäbme ja vuodotäbme, njuoska biergo dadde dievva?


Suormas. -Kansiton ja pohjaton, kuitenkin täynnä tuoretta lihaa?
Sormustin (syyrinki).

13. Manna bejvid, manna ijaid, mutto i goassege uvsa gavdna?


Dimo. -Käy päivät, käy yöt, mutta ei löydä koskaan ovea. Kello.

14. Mi lä dat, go ovta rajge čagna, golma rajge oktanaga itta?


Olmus, mi beski čagna. -Mikä se on, joka menee sisälle yhdestä
rei'ästä, mutta yht'äkkiä näyttäikse kolmesta rei'ästä? Ihminen, joka
pukeutuu lappalaiseen pukuun.

15. Mi čakka sappan bossi, ige sate jorgalet vuovsa basist?


Soabbe. -Mikä mahtuu hiirenreikään eikä saata kääntyä härän
hinkalossa? Sauva.

16. Mi dat lä, mi jokki manna bâsadet ja guodda siskelusaid vissui?


Guödda. -Mikä se on, joka menee joelle pesemään jä kantaa sisukset
kotia? Korvo. (Friis'in tekstissä onrguodda siskelusaid vissui = jättää
sisukset kotona. Epäilemättä guodda = kantaa on parempi).

17. Mi lä ellid dat, mi lä olbmui buok lâgâmusta? Dikke. -Mikä se


elävä on, joka on ihmistä lähinnä? Täi.

18. Mäce čada vagjol ja säjbes mäccai lappa? Nallo. -Kulkee


metsän halki ja jättää häntänsä metsään? Neula.

19. Njalmin borra, niskin bâjka? Häval. -Suulla syöpi, niskasta


oksentaa? Höylä.

20. Njällja oabaš guvlëk ovta roggai? Goattebälljek. -Neljä


sisarusta tirkistävät yhdestä rei'ästä. Teltan seivästen päät.

21. Oajnak galle, mutto gidda ik fatte? Suovva. -Näet sen kyllä,
mutta et voi siihen tarttua? Savu.

22. Okta gäčča vuölas ja čacce golga vuösta-luökkai? Hästa go


jukka. -Joku katsoo alaspäin ja vesi kulkee, ylöspäin? Juova
hevonen.

23. Olmaj färko ja smakkok gačadëk, ige gullu? Muotta. -Mies


hakkaa, lastut putoavat, eikä mitään kuulu? Lumi.

24. Ouda-gäčče dego gagga ja gasko dego farpal ja manna-gäčče


dego suopal? Hästa. -Etu-puoli kuin vati, keskikohta kuin tynnyri ja
takapuoli kuin luuta? Hevonen.

25. Roakke bajas, roakke vuölas ja mokke gasko? Skirtek. -Vekara


ylöspäin, vekara alaspäin ja käyrä keskellä? Patakoukku.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like