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 UserDict


UserDict is a wrapper for dictionaries that makes it easier to subclass the dict class. It has been largely replaced by the ability to subclass dict directly, but it does make it easier to work with as it allows the underlying dictionary to be accessible as an attribute. Its primary use is for backwards-compatibility, that is, versions older then Python 2.2, so if you don't need the compatibility, it is generally better to just subclass dict.

The only special thing the UserDict has beyond the normal dictionary operations is a single attribute:

  • data: A real dictionary to hold the contents of the UserDict class

When a UserDict is created, it accepts an optional argument of the initial data it is to hold; this initial data is accessible by the data attribute.

How to do it...

  1. UserDict is very simple to use. Create an instance of a UserDict and provide a mapping to it:
      >>> from collections import UserDict
      >>> a = UserDict(a=1)
      >>> d...