Designing objects with type hints

The Python type hints provide considerable help in defining objects for a shelf. Throughout this chapter, we'll emphasize the use of the @dataclass decorator to create objects suitable for persistence.

The data class concept is helpful because it makes the attributes that define object state extremely clear. The attributes are not concealed inside method definitions. Without @dataclass, the attributes are often implied by the __init__() method. In some classes, however, attributes are defined dynamically, making the attributes inconsistent and leading to possible problems in recovering object state from a shelved representation.

The pickle module is used to do the serialization of the objects. For more information on object pickling, see Chapter 10Serializing and Saving – JSON, YAML, Pickle, CSV, and XML.

In the following sections, we'll look at ways to define the keys used to uniquely identify objects in a shelf collection. A single unique key is essential. In some problem domains, there will be an attribute, or combination of attributes, that is unique. In spite of this, it's often advantageous to create a surrogate key that is generated by the application and assigned to each persistent object to assure uniqueness.

Let's see how to design keys for our objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset