Book Image

Mastering Python Design Patterns

By : Sakis Kasampalis
Book Image

Mastering Python Design Patterns

By: Sakis Kasampalis

Overview of this book

Table of Contents (23 chapters)
Mastering Python Design Patterns
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
The Factory Pattern
Index

A software example


Python's sorted() and list.sort() functions are examples of the Strategy pattern. Both functions accept a named parameter key, which is basically the name of the function that implements a sorting Strategy [Eckel08, page 202].

The following example (the code is in the langs.py file) shows how two different strategies can be used to sort programming languages in the following ways:

  • Alphabetically

  • Based on their popularity (using the TIOBE index [j.mp/tiobe14])

A namedtuple programming language [j.mp/namedtuple] is used to keep the statistics of the programming languages. A named tuple is an easy-to-create, lightweight, immutable object type. It is compatible with a normal tuple but it can also be treated as an object (can be called by name, using the usual class notation). A named tuple can be used [j.mp/sonamed]:

  • Instead of a class when we want to focus on immutability

  • Instead of a tuple, when it makes sense to use the object notation to create more readable code

I took the liberty...