Book Image

Secret Recipes of the Python Ninja

Book Image

Secret Recipes of the Python Ninja

Overview of this book

This book covers the unexplored secrets of Python, delve into its depths, and uncover its mysteries. You’ll unearth secrets related to the implementation of the standard library, by looking at how modules actually work. You’ll understand the implementation of collections, decimals, and fraction modules. If you haven’t used decorators, coroutines, and generator functions much before, as you make your way through the recipes, you’ll learn what you’ve been missing out on. We’ll cover internal special methods in detail, so you understand what they are and how they can be used to improve the engineering decisions you make. Next, you’ll explore the CPython interpreter, which is a treasure trove of secret hacks that not many programmers are aware of. We’ll take you through the depths of the PyPy project, where you’ll come across several exciting ways that you can improve speed and concurrency. Finally, we’ll take time to explore the PEPs of the latest versions to discover some interesting hacks.
Table of Contents (17 chapters)
Title Page
Copyright and Credits
Packt Upsell
Foreword
Contributors
Preface
Index

Implementing defaultdict


Another dictionary subclass, defaultdict calls a factory function to provide missing values; basically, it creates any items that you try to access, but only if they don't currently exist. This way, you don't get KeyError when trying to access a non-existent key.

All the standard dictionary methods are available, as well as the following:

  • __missing__(key): This method is used by the dict class __getitem__() method when the requested key is not found. Whatever key it returns (or an exception if no key is present) is passed to __getitem__(), which processes it accordingly.

    Assuming the default_factory is not None, this method calls the factory to receive a default value for key, which is then placed in the dictionary as the key, and then returns back to the caller. If the factory value is None, then an exception is thrown with the key as the argument. If the default_factory raises an exception on its own, then the exception is passed along unaltered.

    The __missing__()...