Book Image

Expert Python Programming - Third Edition

By : Michał Jaworski, Tarek Ziadé
Book Image

Expert Python Programming - Third Edition

By: Michał Jaworski, Tarek Ziadé

Overview of this book

Python is a dynamic programming language that's used in a wide range of domains thanks to its simple yet powerful nature. Although writing Python code is easy, making it readable, reusable, and easy to maintain is challenging. Complete with best practices, useful tools, and standards implemented by professional Python developers, the third edition of Expert Python Programming will help you overcome this challenge. The book will start by taking you through the new features in Python 3.7. You'll then learn the advanced components of Python syntax, in addition to understanding how to apply concepts of various programming paradigms, including object-oriented programming, functional programming, and event-driven programming. This book will also guide you through learning the naming best practices, writing your own distributable Python packages, and getting up to speed with automated ways to deploy your software on remote servers. You’ll discover how to create useful Python extensions with C, C++, Cython, and CFFI. Furthermore, studying about code management tools, writing clear documentation, and exploring test-driven development will help you write clean code. By the end of the book, you will have become an expert in writing efficient and maintainable Python code.
Table of Contents (25 chapters)
Free Chapter
1
Section 1: Before You Start
4
Section 2: Python Craftsmanship
12
Section 3: Quality over Quantity
16
Section 4: Need for Speed
20
Section 5: Technical Architecture
23
reStructuredText Primer

Subclassing built-in types

Subclassing built-in types in Python is pretty straightforward. A built-in type, called object is a common ancestor for all built-in types, as well as for all user-defined classes that have no explicit parent class specified. Thanks to this, every time you need to implement a class that behaves almost like one of the built-in types, the best practice is to subtype it.

Now, we will look at the code for a class called distinctdict, which uses this technique. It will be a subclass of the usual Python dict type. This new class will behave, in most ways, like an ordinary Python dict type. But, instead of allowing multiple keys with the same value, when someone tries to add a new entry with an identical value, it raises a ValueError subclass with a help message.

As already stated, the built-in dict type is an object subclass:

>>> isinstance(dict(...