Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 1 | .. _descriptorhowto: |
| 2 | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 3 | ====================== |
| 4 | Descriptor HowTo Guide |
| 5 | ====================== |
| 6 | |
| 7 | :Author: Raymond Hettinger |
| 8 | :Contact: <python at rcn dot com> |
| 9 | |
| 10 | .. Contents:: |
| 11 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 12 | |
| 13 | :term:`Descriptors <descriptor>` let objects customize attribute lookup, |
| 14 | storage, and deletion. |
| 15 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 16 | This guide has four major sections: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 17 | |
| 18 | 1) The "primer" gives a basic overview, moving gently from simple examples, |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 19 | adding one feature at a time. Start here if you're new to descriptors. |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 20 | |
| 21 | 2) The second section shows a complete, practical descriptor example. If you |
| 22 | already know the basics, start there. |
| 23 | |
| 24 | 3) The third section provides a more technical tutorial that goes into the |
| 25 | detailed mechanics of how descriptors work. Most people don't need this |
| 26 | level of detail. |
| 27 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 28 | 4) The last section has pure Python equivalents for built-in descriptors that |
| 29 | are written in C. Read this if you're curious about how functions turn |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 30 | into bound methods or about the implementation of common tools like |
| 31 | :func:`classmethod`, :func:`staticmethod`, :func:`property`, and |
| 32 | :term:`__slots__`. |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 33 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 34 | |
| 35 | Primer |
| 36 | ^^^^^^ |
| 37 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 38 | In this primer, we start with the most basic possible example and then we'll |
| 39 | add new capabilities one by one. |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 40 | |
| 41 | |
| 42 | Simple example: A descriptor that returns a constant |
| 43 | ---------------------------------------------------- |
| 44 | |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 45 | The :class:`Ten` class is a descriptor that always returns the constant ``10`` |
| 46 | from its :meth:`__get__` method:: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 47 | |
| 48 | |
| 49 | class Ten: |
| 50 | def __get__(self, obj, objtype=None): |
| 51 | return 10 |
| 52 | |
| 53 | To use the descriptor, it must be stored as a class variable in another class:: |
| 54 | |
| 55 | class A: |
| 56 | x = 5 # Regular class attribute |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 57 | y = Ten() # Descriptor instance |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 58 | |
| 59 | An interactive session shows the difference between normal attribute lookup |
| 60 | and descriptor lookup:: |
| 61 | |
| 62 | >>> a = A() # Make an instance of class A |
| 63 | >>> a.x # Normal attribute lookup |
| 64 | 5 |
| 65 | >>> a.y # Descriptor lookup |
| 66 | 10 |
| 67 | |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 68 | In the ``a.x`` attribute lookup, the dot operator finds the key ``x`` and the |
| 69 | value ``5`` in the class dictionary. In the ``a.y`` lookup, the dot operator |
| 70 | finds a descriptor instance, recognized by its ``__get__`` method, and calls |
| 71 | that method which returns ``10``. |
| 72 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 73 | Note that the value ``10`` is not stored in either the class dictionary or the |
| 74 | instance dictionary. Instead, the value ``10`` is computed on demand. |
| 75 | |
| 76 | This example shows how a simple descriptor works, but it isn't very useful. |
| 77 | For retrieving constants, normal attribute lookup would be better. |
| 78 | |
| 79 | In the next section, we'll create something more useful, a dynamic lookup. |
| 80 | |
| 81 | |
| 82 | Dynamic lookups |
| 83 | --------------- |
| 84 | |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 85 | Interesting descriptors typically run computations instead of returning |
| 86 | constants:: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 87 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 88 | import os |
| 89 | |
| 90 | class DirectorySize: |
| 91 | |
| 92 | def __get__(self, obj, objtype=None): |
| 93 | return len(os.listdir(obj.dirname)) |
| 94 | |
| 95 | class Directory: |
| 96 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 97 | size = DirectorySize() # Descriptor instance |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 98 | |
| 99 | def __init__(self, dirname): |
| 100 | self.dirname = dirname # Regular instance attribute |
| 101 | |
| 102 | An interactive session shows that the lookup is dynamic — it computes |
| 103 | different, updated answers each time:: |
| 104 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 105 | >>> s = Directory('songs') |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 106 | >>> g = Directory('games') |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 107 | >>> s.size # The songs directory has twenty files |
| 108 | 20 |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 109 | >>> g.size # The games directory has three files |
| 110 | 3 |
| 111 | >>> open('games/newfile').close() # Add a fourth file to the directory |
| 112 | >>> g.size # File count is automatically updated |
| 113 | 4 |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 114 | |
| 115 | Besides showing how descriptors can run computations, this example also |
| 116 | reveals the purpose of the parameters to :meth:`__get__`. The *self* |
| 117 | parameter is *size*, an instance of *DirectorySize*. The *obj* parameter is |
Raymond Hettinger | 8031877 | 2020-11-06 01:30:17 -0800 | [diff] [blame] | 118 | either *g* or *s*, an instance of *Directory*. It is the *obj* parameter that |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 119 | lets the :meth:`__get__` method learn the target directory. The *objtype* |
| 120 | parameter is the class *Directory*. |
| 121 | |
| 122 | |
| 123 | Managed attributes |
| 124 | ------------------ |
| 125 | |
| 126 | A popular use for descriptors is managing access to instance data. The |
| 127 | descriptor is assigned to a public attribute in the class dictionary while the |
| 128 | actual data is stored as a private attribute in the instance dictionary. The |
| 129 | descriptor's :meth:`__get__` and :meth:`__set__` methods are triggered when |
| 130 | the public attribute is accessed. |
| 131 | |
| 132 | In the following example, *age* is the public attribute and *_age* is the |
| 133 | private attribute. When the public attribute is accessed, the descriptor logs |
| 134 | the lookup or update:: |
| 135 | |
| 136 | import logging |
| 137 | |
| 138 | logging.basicConfig(level=logging.INFO) |
| 139 | |
| 140 | class LoggedAgeAccess: |
| 141 | |
| 142 | def __get__(self, obj, objtype=None): |
| 143 | value = obj._age |
| 144 | logging.info('Accessing %r giving %r', 'age', value) |
| 145 | return value |
| 146 | |
| 147 | def __set__(self, obj, value): |
| 148 | logging.info('Updating %r to %r', 'age', value) |
| 149 | obj._age = value |
| 150 | |
| 151 | class Person: |
| 152 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 153 | age = LoggedAgeAccess() # Descriptor instance |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 154 | |
| 155 | def __init__(self, name, age): |
| 156 | self.name = name # Regular instance attribute |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 157 | self.age = age # Calls __set__() |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 158 | |
| 159 | def birthday(self): |
| 160 | self.age += 1 # Calls both __get__() and __set__() |
| 161 | |
| 162 | |
| 163 | An interactive session shows that all access to the managed attribute *age* is |
| 164 | logged, but that the regular attribute *name* is not logged:: |
| 165 | |
| 166 | >>> mary = Person('Mary M', 30) # The initial age update is logged |
| 167 | INFO:root:Updating 'age' to 30 |
| 168 | >>> dave = Person('David D', 40) |
| 169 | INFO:root:Updating 'age' to 40 |
| 170 | |
| 171 | >>> vars(mary) # The actual data is in a private attribute |
| 172 | {'name': 'Mary M', '_age': 30} |
| 173 | >>> vars(dave) |
| 174 | {'name': 'David D', '_age': 40} |
| 175 | |
| 176 | >>> mary.age # Access the data and log the lookup |
| 177 | INFO:root:Accessing 'age' giving 30 |
| 178 | 30 |
| 179 | >>> mary.birthday() # Updates are logged as well |
| 180 | INFO:root:Accessing 'age' giving 30 |
| 181 | INFO:root:Updating 'age' to 31 |
| 182 | |
| 183 | >>> dave.name # Regular attribute lookup isn't logged |
| 184 | 'David D' |
| 185 | >>> dave.age # Only the managed attribute is logged |
| 186 | INFO:root:Accessing 'age' giving 40 |
| 187 | 40 |
| 188 | |
Raymond Hettinger | 8031877 | 2020-11-06 01:30:17 -0800 | [diff] [blame] | 189 | One major issue with this example is that the private name *_age* is hardwired in |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 190 | the *LoggedAgeAccess* class. That means that each instance can only have one |
| 191 | logged attribute and that its name is unchangeable. In the next example, |
| 192 | we'll fix that problem. |
| 193 | |
| 194 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 195 | Customized names |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 196 | ---------------- |
| 197 | |
Raymond Hettinger | 8031877 | 2020-11-06 01:30:17 -0800 | [diff] [blame] | 198 | When a class uses descriptors, it can inform each descriptor about which |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 199 | variable name was used. |
| 200 | |
| 201 | In this example, the :class:`Person` class has two descriptor instances, |
| 202 | *name* and *age*. When the :class:`Person` class is defined, it makes a |
| 203 | callback to :meth:`__set_name__` in *LoggedAccess* so that the field names can |
| 204 | be recorded, giving each descriptor its own *public_name* and *private_name*:: |
| 205 | |
| 206 | import logging |
| 207 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 208 | logging.basicConfig(level=logging.INFO) |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 209 | |
| 210 | class LoggedAccess: |
| 211 | |
| 212 | def __set_name__(self, owner, name): |
| 213 | self.public_name = name |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 214 | self.private_name = '_' + name |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 215 | |
| 216 | def __get__(self, obj, objtype=None): |
| 217 | value = getattr(obj, self.private_name) |
| 218 | logging.info('Accessing %r giving %r', self.public_name, value) |
| 219 | return value |
| 220 | |
| 221 | def __set__(self, obj, value): |
| 222 | logging.info('Updating %r to %r', self.public_name, value) |
| 223 | setattr(obj, self.private_name, value) |
| 224 | |
| 225 | class Person: |
| 226 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 227 | name = LoggedAccess() # First descriptor instance |
| 228 | age = LoggedAccess() # Second descriptor instance |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 229 | |
| 230 | def __init__(self, name, age): |
| 231 | self.name = name # Calls the first descriptor |
| 232 | self.age = age # Calls the second descriptor |
| 233 | |
| 234 | def birthday(self): |
| 235 | self.age += 1 |
| 236 | |
| 237 | An interactive session shows that the :class:`Person` class has called |
| 238 | :meth:`__set_name__` so that the field names would be recorded. Here |
Raymond Hettinger | 8031877 | 2020-11-06 01:30:17 -0800 | [diff] [blame] | 239 | we call :func:`vars` to look up the descriptor without triggering it:: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 240 | |
| 241 | >>> vars(vars(Person)['name']) |
| 242 | {'public_name': 'name', 'private_name': '_name'} |
| 243 | >>> vars(vars(Person)['age']) |
| 244 | {'public_name': 'age', 'private_name': '_age'} |
| 245 | |
| 246 | The new class now logs access to both *name* and *age*:: |
| 247 | |
| 248 | >>> pete = Person('Peter P', 10) |
| 249 | INFO:root:Updating 'name' to 'Peter P' |
| 250 | INFO:root:Updating 'age' to 10 |
| 251 | >>> kate = Person('Catherine C', 20) |
| 252 | INFO:root:Updating 'name' to 'Catherine C' |
| 253 | INFO:root:Updating 'age' to 20 |
| 254 | |
| 255 | The two *Person* instances contain only the private names:: |
| 256 | |
| 257 | >>> vars(pete) |
| 258 | {'_name': 'Peter P', '_age': 10} |
| 259 | >>> vars(kate) |
| 260 | {'_name': 'Catherine C', '_age': 20} |
| 261 | |
| 262 | |
| 263 | Closing thoughts |
| 264 | ---------------- |
| 265 | |
| 266 | A :term:`descriptor` is what we call any object that defines :meth:`__get__`, |
| 267 | :meth:`__set__`, or :meth:`__delete__`. |
| 268 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 269 | Optionally, descriptors can have a :meth:`__set_name__` method. This is only |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 270 | used in cases where a descriptor needs to know either the class where it was |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 271 | created or the name of class variable it was assigned to. (This method, if |
| 272 | present, is called even if the class is not a descriptor.) |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 273 | |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 274 | Descriptors get invoked by the dot "operator" during attribute lookup. If a |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 275 | descriptor is accessed indirectly with ``vars(some_class)[descriptor_name]``, |
| 276 | the descriptor instance is returned without invoking it. |
| 277 | |
| 278 | Descriptors only work when used as class variables. When put in instances, |
| 279 | they have no effect. |
| 280 | |
| 281 | The main motivation for descriptors is to provide a hook allowing objects |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 282 | stored in class variables to control what happens during attribute lookup. |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 283 | |
| 284 | Traditionally, the calling class controls what happens during lookup. |
| 285 | Descriptors invert that relationship and allow the data being looked-up to |
| 286 | have a say in the matter. |
| 287 | |
| 288 | Descriptors are used throughout the language. It is how functions turn into |
| 289 | bound methods. Common tools like :func:`classmethod`, :func:`staticmethod`, |
| 290 | :func:`property`, and :func:`functools.cached_property` are all implemented as |
| 291 | descriptors. |
| 292 | |
| 293 | |
| 294 | Complete Practical Example |
| 295 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 296 | |
| 297 | In this example, we create a practical and powerful tool for locating |
| 298 | notoriously hard to find data corruption bugs. |
| 299 | |
| 300 | |
| 301 | Validator class |
| 302 | --------------- |
| 303 | |
| 304 | A validator is a descriptor for managed attribute access. Prior to storing |
| 305 | any data, it verifies that the new value meets various type and range |
| 306 | restrictions. If those restrictions aren't met, it raises an exception to |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 307 | prevent data corruption at its source. |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 308 | |
| 309 | This :class:`Validator` class is both an :term:`abstract base class` and a |
| 310 | managed attribute descriptor:: |
| 311 | |
| 312 | from abc import ABC, abstractmethod |
| 313 | |
| 314 | class Validator(ABC): |
| 315 | |
| 316 | def __set_name__(self, owner, name): |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 317 | self.private_name = '_' + name |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 318 | |
| 319 | def __get__(self, obj, objtype=None): |
| 320 | return getattr(obj, self.private_name) |
| 321 | |
| 322 | def __set__(self, obj, value): |
| 323 | self.validate(value) |
| 324 | setattr(obj, self.private_name, value) |
| 325 | |
| 326 | @abstractmethod |
| 327 | def validate(self, value): |
| 328 | pass |
| 329 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 330 | Custom validators need to inherit from :class:`Validator` and must supply a |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 331 | :meth:`validate` method to test various restrictions as needed. |
| 332 | |
| 333 | |
| 334 | Custom validators |
| 335 | ----------------- |
| 336 | |
| 337 | Here are three practical data validation utilities: |
| 338 | |
| 339 | 1) :class:`OneOf` verifies that a value is one of a restricted set of options. |
| 340 | |
| 341 | 2) :class:`Number` verifies that a value is either an :class:`int` or |
| 342 | :class:`float`. Optionally, it verifies that a value is between a given |
| 343 | minimum or maximum. |
| 344 | |
| 345 | 3) :class:`String` verifies that a value is a :class:`str`. Optionally, it |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 346 | validates a given minimum or maximum length. It can validate a |
| 347 | user-defined `predicate |
| 348 | <https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)>`_ as well. |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 349 | |
| 350 | :: |
| 351 | |
| 352 | class OneOf(Validator): |
| 353 | |
| 354 | def __init__(self, *options): |
| 355 | self.options = set(options) |
| 356 | |
| 357 | def validate(self, value): |
| 358 | if value not in self.options: |
| 359 | raise ValueError(f'Expected {value!r} to be one of {self.options!r}') |
| 360 | |
| 361 | class Number(Validator): |
| 362 | |
| 363 | def __init__(self, minvalue=None, maxvalue=None): |
| 364 | self.minvalue = minvalue |
| 365 | self.maxvalue = maxvalue |
| 366 | |
| 367 | def validate(self, value): |
| 368 | if not isinstance(value, (int, float)): |
| 369 | raise TypeError(f'Expected {value!r} to be an int or float') |
| 370 | if self.minvalue is not None and value < self.minvalue: |
| 371 | raise ValueError( |
| 372 | f'Expected {value!r} to be at least {self.minvalue!r}' |
| 373 | ) |
| 374 | if self.maxvalue is not None and value > self.maxvalue: |
| 375 | raise ValueError( |
| 376 | f'Expected {value!r} to be no more than {self.maxvalue!r}' |
| 377 | ) |
| 378 | |
| 379 | class String(Validator): |
| 380 | |
| 381 | def __init__(self, minsize=None, maxsize=None, predicate=None): |
| 382 | self.minsize = minsize |
| 383 | self.maxsize = maxsize |
| 384 | self.predicate = predicate |
| 385 | |
| 386 | def validate(self, value): |
| 387 | if not isinstance(value, str): |
| 388 | raise TypeError(f'Expected {value!r} to be an str') |
| 389 | if self.minsize is not None and len(value) < self.minsize: |
| 390 | raise ValueError( |
| 391 | f'Expected {value!r} to be no smaller than {self.minsize!r}' |
| 392 | ) |
| 393 | if self.maxsize is not None and len(value) > self.maxsize: |
| 394 | raise ValueError( |
| 395 | f'Expected {value!r} to be no bigger than {self.maxsize!r}' |
| 396 | ) |
| 397 | if self.predicate is not None and not self.predicate(value): |
| 398 | raise ValueError( |
| 399 | f'Expected {self.predicate} to be true for {value!r}' |
| 400 | ) |
| 401 | |
| 402 | |
| 403 | Practical use |
| 404 | ------------- |
| 405 | |
| 406 | Here's how the data validators can be used in a real class:: |
| 407 | |
| 408 | class Component: |
| 409 | |
| 410 | name = String(minsize=3, maxsize=10, predicate=str.isupper) |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 411 | kind = OneOf('wood', 'metal', 'plastic') |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 412 | quantity = Number(minvalue=0) |
| 413 | |
| 414 | def __init__(self, name, kind, quantity): |
| 415 | self.name = name |
| 416 | self.kind = kind |
| 417 | self.quantity = quantity |
| 418 | |
| 419 | The descriptors prevent invalid instances from being created:: |
| 420 | |
| 421 | Component('WIDGET', 'metal', 5) # Allowed. |
| 422 | Component('Widget', 'metal', 5) # Blocked: 'Widget' is not all uppercase |
| 423 | Component('WIDGET', 'metle', 5) # Blocked: 'metle' is misspelled |
| 424 | Component('WIDGET', 'metal', -5) # Blocked: -5 is negative |
| 425 | Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number |
| 426 | |
| 427 | |
| 428 | Technical Tutorial |
| 429 | ^^^^^^^^^^^^^^^^^^ |
| 430 | |
| 431 | What follows is a more technical tutorial for the mechanics and details of how |
| 432 | descriptors work. |
| 433 | |
| 434 | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 435 | Abstract |
| 436 | -------- |
| 437 | |
| 438 | Defines descriptors, summarizes the protocol, and shows how descriptors are |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 439 | called. Provides an example showing how object relational mappings work. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 440 | |
| 441 | Learning about descriptors not only provides access to a larger toolset, it |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 442 | creates a deeper understanding of how Python works. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 443 | |
| 444 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 445 | Definition and introduction |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 446 | --------------------------- |
| 447 | |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 448 | In general, a descriptor is an attribute value that has one of the methods in |
| 449 | the descriptor protocol. Those methods are :meth:`__get__`, :meth:`__set__`, |
| 450 | and :meth:`__delete__`. If any of those methods are defined for an the |
| 451 | attribute, it is said to be a :term:`descriptor`. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 452 | |
| 453 | The default behavior for attribute access is to get, set, or delete the |
| 454 | attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain |
| 455 | starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 456 | continuing through the method resolution order of ``type(a)``. If the |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 457 | looked-up value is an object defining one of the descriptor methods, then Python |
| 458 | may override the default behavior and invoke the descriptor method instead. |
| 459 | Where this occurs in the precedence chain depends on which descriptor methods |
Florent Xicluna | aa6c1d2 | 2011-12-12 18:54:29 +0100 | [diff] [blame] | 460 | were defined. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 461 | |
| 462 | Descriptors are a powerful, general purpose protocol. They are the mechanism |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 463 | behind properties, methods, static methods, class methods, and |
| 464 | :func:`super()`. They are used throughout Python itself. Descriptors |
| 465 | simplify the underlying C code and offer a flexible set of new tools for |
| 466 | everyday Python programs. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 467 | |
| 468 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 469 | Descriptor protocol |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 470 | ------------------- |
| 471 | |
NotAFile | 28ea4c2 | 2018-09-10 23:35:38 +0200 | [diff] [blame] | 472 | ``descr.__get__(self, obj, type=None) -> value`` |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 473 | |
NotAFile | 28ea4c2 | 2018-09-10 23:35:38 +0200 | [diff] [blame] | 474 | ``descr.__set__(self, obj, value) -> None`` |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 475 | |
NotAFile | 28ea4c2 | 2018-09-10 23:35:38 +0200 | [diff] [blame] | 476 | ``descr.__delete__(self, obj) -> None`` |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 477 | |
| 478 | That is all there is to it. Define any of these methods and an object is |
| 479 | considered a descriptor and can override default behavior upon being looked up |
| 480 | as an attribute. |
| 481 | |
Aaron Hall, MBA | 4054b17 | 2018-05-20 19:46:42 -0400 | [diff] [blame] | 482 | If an object defines :meth:`__set__` or :meth:`__delete__`, it is considered |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 483 | a data descriptor. Descriptors that only define :meth:`__get__` are called |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 484 | non-data descriptors (they are often used for methods but other uses are |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 485 | possible). |
| 486 | |
| 487 | Data and non-data descriptors differ in how overrides are calculated with |
| 488 | respect to entries in an instance's dictionary. If an instance's dictionary |
| 489 | has an entry with the same name as a data descriptor, the data descriptor |
| 490 | takes precedence. If an instance's dictionary has an entry with the same |
| 491 | name as a non-data descriptor, the dictionary entry takes precedence. |
| 492 | |
| 493 | To make a read-only data descriptor, define both :meth:`__get__` and |
| 494 | :meth:`__set__` with the :meth:`__set__` raising an :exc:`AttributeError` when |
| 495 | called. Defining the :meth:`__set__` method with an exception raising |
| 496 | placeholder is enough to make it a data descriptor. |
| 497 | |
| 498 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 499 | Overview of descriptor invocation |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 500 | --------------------------------- |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 501 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 502 | A descriptor can be called directly with ``desc.__get__(obj)`` or |
| 503 | ``desc.__get__(None, cls)``. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 504 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 505 | But it is more common for a descriptor to be invoked automatically from |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 506 | attribute access. |
| 507 | |
| 508 | The expression ``obj.x`` looks up the attribute ``x`` in the chain of |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 509 | namespaces for ``obj``. If the search finds a descriptor outside of the |
| 510 | instance ``__dict__``, its :meth:`__get__` method is invoked according to the |
| 511 | precedence rules listed below. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 512 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 513 | The details of invocation depend on whether ``obj`` is an object, class, or |
| 514 | instance of super. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 515 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 516 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 517 | Invocation from an instance |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 518 | --------------------------- |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 519 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 520 | Instance lookup scans through a chain of namespaces giving data descriptors |
| 521 | the highest priority, followed by instance variables, then non-data |
| 522 | descriptors, then class variables, and lastly :meth:`__getattr__` if it is |
| 523 | provided. |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 524 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 525 | If a descriptor is found for ``a.x``, then it is invoked with: |
| 526 | ``desc.__get__(a, type(a))``. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 527 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 528 | The logic for a dotted lookup is in :meth:`object.__getattribute__`. Here is |
| 529 | a pure Python equivalent:: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 530 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 531 | def object_getattribute(obj, name): |
| 532 | "Emulate PyObject_GenericGetAttr() in Objects/object.c" |
| 533 | null = object() |
| 534 | objtype = type(obj) |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 535 | cls_var = getattr(objtype, name, null) |
| 536 | descr_get = getattr(type(cls_var), '__get__', null) |
| 537 | if descr_get is not null: |
| 538 | if (hasattr(type(cls_var), '__set__') |
| 539 | or hasattr(type(cls_var), '__delete__')): |
| 540 | return descr_get(cls_var, obj, objtype) # data descriptor |
| 541 | if hasattr(obj, '__dict__') and name in vars(obj): |
| 542 | return vars(obj)[name] # instance variable |
| 543 | if descr_get is not null: |
| 544 | return descr_get(cls_var, obj, objtype) # non-data descriptor |
| 545 | if cls_var is not null: |
| 546 | return cls_var # class variable |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 547 | raise AttributeError(name) |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 548 | |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 549 | Interestingly, attribute lookup doesn't call :meth:`object.__getattribute__` |
| 550 | directly. Instead, both the dot operator and the :func:`getattr` function |
| 551 | perform attribute lookup by way of a helper function:: |
| 552 | |
| 553 | def getattr_hook(obj, name): |
| 554 | "Emulate slot_tp_getattr_hook() in Objects/typeobject.c" |
| 555 | try: |
| 556 | return obj.__getattribute__(name) |
| 557 | except AttributeError: |
| 558 | if not hasattr(type(obj), '__getattr__'): |
| 559 | raise |
| 560 | return type(obj).__getattr__(obj, name) # __getattr__ |
| 561 | |
| 562 | So if :meth:`__getattr__` exists, it is called whenever :meth:`__getattribute__` |
| 563 | raises :exc:`AttributeError` (either directly or in one of the descriptor calls). |
| 564 | |
| 565 | Also, if a user calls :meth:`object.__getattribute__` directly, the |
| 566 | :meth:`__getattr__` hook is bypassed entirely. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 567 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 568 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 569 | Invocation from a class |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 570 | ----------------------- |
| 571 | |
| 572 | The logic for a dotted lookup such as ``A.x`` is in |
| 573 | :meth:`type.__getattribute__`. The steps are similar to those for |
| 574 | :meth:`object.__getattribute__` but the instance dictionary lookup is replaced |
| 575 | by a search through the class's :term:`method resolution order`. |
| 576 | |
| 577 | If a descriptor is found, it is invoked with ``desc.__get__(None, A)``. |
| 578 | |
| 579 | The full C implementation can be found in :c:func:`type_getattro()` and |
| 580 | :c:func:`_PyType_Lookup()` in :source:`Objects/typeobject.c`. |
| 581 | |
| 582 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 583 | Invocation from super |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 584 | --------------------- |
| 585 | |
| 586 | The logic for super's dotted lookup is in the :meth:`__getattribute__` method for |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 587 | object returned by :class:`super()`. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 588 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 589 | A dotted lookup such as ``super(A, obj).m`` searches ``obj.__class__.__mro__`` |
| 590 | for the base class ``B`` immediately following ``A`` and then returns |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 591 | ``B.__dict__['m'].__get__(obj, A)``. If not a descriptor, ``m`` is returned |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 592 | unchanged. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 593 | |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 594 | The full C implementation can be found in :c:func:`super_getattro()` in |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 595 | :source:`Objects/typeobject.c`. A pure Python equivalent can be found in |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 596 | `Guido's Tutorial |
| 597 | <https://www.python.org/download/releases/2.2.3/descrintro/#cooperation>`_. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 598 | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 599 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 600 | Summary of invocation logic |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 601 | --------------------------- |
| 602 | |
| 603 | The mechanism for descriptors is embedded in the :meth:`__getattribute__()` |
| 604 | methods for :class:`object`, :class:`type`, and :func:`super`. |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 605 | |
| 606 | The important points to remember are: |
| 607 | |
| 608 | * Descriptors are invoked by the :meth:`__getattribute__` method. |
| 609 | |
| 610 | * Classes inherit this machinery from :class:`object`, :class:`type`, or |
| 611 | :func:`super`. |
| 612 | |
| 613 | * Overriding :meth:`__getattribute__` prevents automatic descriptor calls |
| 614 | because all the descriptor logic is in that method. |
| 615 | |
| 616 | * :meth:`object.__getattribute__` and :meth:`type.__getattribute__` make |
| 617 | different calls to :meth:`__get__`. The first includes the instance and may |
| 618 | include the class. The second puts in ``None`` for the instance and always |
| 619 | includes the class. |
| 620 | |
| 621 | * Data descriptors always override instance dictionaries. |
| 622 | |
| 623 | * Non-data descriptors may be overridden by instance dictionaries. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 624 | |
| 625 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 626 | Automatic name notification |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 627 | --------------------------- |
| 628 | |
| 629 | Sometimes it is desirable for a descriptor to know what class variable name it |
| 630 | was assigned to. When a new class is created, the :class:`type` metaclass |
| 631 | scans the dictionary of the new class. If any of the entries are descriptors |
| 632 | and if they define :meth:`__set_name__`, that method is called with two |
Raymond Hettinger | 8031877 | 2020-11-06 01:30:17 -0800 | [diff] [blame] | 633 | arguments. The *owner* is the class where the descriptor is used, and the |
| 634 | *name* is the class variable the descriptor was assigned to. |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 635 | |
| 636 | The implementation details are in :c:func:`type_new()` and |
| 637 | :c:func:`set_names()` in :source:`Objects/typeobject.c`. |
| 638 | |
| 639 | Since the update logic is in :meth:`type.__new__`, notifications only take |
| 640 | place at the time of class creation. If descriptors are added to the class |
| 641 | afterwards, :meth:`__set_name__` will need to be called manually. |
| 642 | |
| 643 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 644 | ORM example |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 645 | ----------- |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 646 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 647 | The following code is simplified skeleton showing how data descriptors could |
| 648 | be used to implement an `object relational mapping |
| 649 | <https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping>`_. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 650 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 651 | The essential idea is that the data is stored in an external database. The |
| 652 | Python instances only hold keys to the database's tables. Descriptors take |
| 653 | care of lookups or updates:: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 654 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 655 | class Field: |
| 656 | |
| 657 | def __set_name__(self, owner, name): |
| 658 | self.fetch = f'SELECT {name} FROM {owner.table} WHERE {owner.key}=?;' |
| 659 | self.store = f'UPDATE {owner.table} SET {name}=? WHERE {owner.key}=?;' |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 660 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 661 | def __get__(self, obj, objtype=None): |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 662 | return conn.execute(self.fetch, [obj.key]).fetchone()[0] |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 663 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 664 | def __set__(self, obj, value): |
| 665 | conn.execute(self.store, [value, obj.key]) |
| 666 | conn.commit() |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 667 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 668 | We can use the :class:`Field` class to define "models" that describe the schema |
| 669 | for each table in a database:: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 670 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 671 | class Movie: |
| 672 | table = 'Movies' # Table name |
| 673 | key = 'title' # Primary key |
| 674 | director = Field() |
| 675 | year = Field() |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 676 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 677 | def __init__(self, key): |
| 678 | self.key = key |
| 679 | |
| 680 | class Song: |
| 681 | table = 'Music' |
| 682 | key = 'title' |
| 683 | artist = Field() |
| 684 | year = Field() |
| 685 | genre = Field() |
| 686 | |
| 687 | def __init__(self, key): |
| 688 | self.key = key |
| 689 | |
| 690 | An interactive session shows how data is retrieved from the database and how |
| 691 | it can be updated:: |
| 692 | |
| 693 | >>> import sqlite3 |
| 694 | >>> conn = sqlite3.connect('entertainment.db') |
| 695 | |
| 696 | >>> Movie('Star Wars').director |
| 697 | 'George Lucas' |
| 698 | >>> jaws = Movie('Jaws') |
| 699 | >>> f'Released in {jaws.year} by {jaws.director}' |
| 700 | 'Released in 1975 by Steven Spielberg' |
| 701 | |
| 702 | >>> Song('Country Roads').artist |
| 703 | 'John Denver' |
| 704 | |
| 705 | >>> Movie('Star Wars').director = 'J.J. Abrams' |
| 706 | >>> Movie('Star Wars').director |
| 707 | 'J.J. Abrams' |
| 708 | |
Raymond Hettinger | c272d40 | 2020-11-15 17:44:28 -0800 | [diff] [blame] | 709 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 710 | Pure Python Equivalents |
| 711 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 712 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 713 | The descriptor protocol is simple and offers exciting possibilities. Several |
Raymond Hettinger | 148c76b | 2020-11-01 09:10:06 -0800 | [diff] [blame] | 714 | use cases are so common that they have been prepackaged into built-in tools. |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 715 | Properties, bound methods, static methods, class methods, and \_\_slots\_\_ are |
| 716 | all based on the descriptor protocol. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 717 | |
| 718 | |
| 719 | Properties |
| 720 | ---------- |
| 721 | |
| 722 | Calling :func:`property` is a succinct way of building a data descriptor that |
Raymond Hettinger | 8031877 | 2020-11-06 01:30:17 -0800 | [diff] [blame] | 723 | triggers a function call upon access to an attribute. Its signature is:: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 724 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 725 | property(fget=None, fset=None, fdel=None, doc=None) -> property |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 726 | |
| 727 | The documentation shows a typical use to define a managed attribute ``x``:: |
| 728 | |
Serhiy Storchaka | e042a45 | 2019-06-10 13:35:52 +0300 | [diff] [blame] | 729 | class C: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 730 | def getx(self): return self.__x |
| 731 | def setx(self, value): self.__x = value |
| 732 | def delx(self): del self.__x |
| 733 | x = property(getx, setx, delx, "I'm the 'x' property.") |
| 734 | |
| 735 | To see how :func:`property` is implemented in terms of the descriptor protocol, |
| 736 | here is a pure Python equivalent:: |
| 737 | |
Serhiy Storchaka | e042a45 | 2019-06-10 13:35:52 +0300 | [diff] [blame] | 738 | class Property: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 739 | "Emulate PyProperty_Type() in Objects/descrobject.c" |
| 740 | |
| 741 | def __init__(self, fget=None, fset=None, fdel=None, doc=None): |
| 742 | self.fget = fget |
| 743 | self.fset = fset |
| 744 | self.fdel = fdel |
Raymond Hettinger | 632c8c8 | 2013-03-10 09:41:18 -0700 | [diff] [blame] | 745 | if doc is None and fget is not None: |
| 746 | doc = fget.__doc__ |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 747 | self.__doc__ = doc |
| 748 | |
| 749 | def __get__(self, obj, objtype=None): |
| 750 | if obj is None: |
| 751 | return self |
| 752 | if self.fget is None: |
Raymond Hettinger | 632c8c8 | 2013-03-10 09:41:18 -0700 | [diff] [blame] | 753 | raise AttributeError("unreadable attribute") |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 754 | return self.fget(obj) |
| 755 | |
| 756 | def __set__(self, obj, value): |
| 757 | if self.fset is None: |
Raymond Hettinger | 632c8c8 | 2013-03-10 09:41:18 -0700 | [diff] [blame] | 758 | raise AttributeError("can't set attribute") |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 759 | self.fset(obj, value) |
| 760 | |
| 761 | def __delete__(self, obj): |
| 762 | if self.fdel is None: |
Raymond Hettinger | 632c8c8 | 2013-03-10 09:41:18 -0700 | [diff] [blame] | 763 | raise AttributeError("can't delete attribute") |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 764 | self.fdel(obj) |
| 765 | |
Raymond Hettinger | 632c8c8 | 2013-03-10 09:41:18 -0700 | [diff] [blame] | 766 | def getter(self, fget): |
| 767 | return type(self)(fget, self.fset, self.fdel, self.__doc__) |
| 768 | |
| 769 | def setter(self, fset): |
| 770 | return type(self)(self.fget, fset, self.fdel, self.__doc__) |
| 771 | |
| 772 | def deleter(self, fdel): |
| 773 | return type(self)(self.fget, self.fset, fdel, self.__doc__) |
| 774 | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 775 | The :func:`property` builtin helps whenever a user interface has granted |
| 776 | attribute access and then subsequent changes require the intervention of a |
| 777 | method. |
| 778 | |
| 779 | For instance, a spreadsheet class may grant access to a cell value through |
| 780 | ``Cell('b10').value``. Subsequent improvements to the program require the cell |
| 781 | to be recalculated on every access; however, the programmer does not want to |
| 782 | affect existing client code accessing the attribute directly. The solution is |
| 783 | to wrap access to the value attribute in a property data descriptor:: |
| 784 | |
Serhiy Storchaka | e042a45 | 2019-06-10 13:35:52 +0300 | [diff] [blame] | 785 | class Cell: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 786 | ... |
| 787 | |
| 788 | @property |
| 789 | def value(self): |
_ = NaN | b066edf | 2017-06-23 11:54:35 +0800 | [diff] [blame] | 790 | "Recalculate the cell before returning value" |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 791 | self.recalc() |
_ = NaN | b066edf | 2017-06-23 11:54:35 +0800 | [diff] [blame] | 792 | return self._value |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 793 | |
| 794 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 795 | Functions and methods |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 796 | --------------------- |
| 797 | |
| 798 | Python's object oriented features are built upon a function based environment. |
| 799 | Using non-data descriptors, the two are merged seamlessly. |
| 800 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 801 | Functions stored in class dictionaries get turned into methods when invoked. |
| 802 | Methods only differ from regular functions in that the object instance is |
| 803 | prepended to the other arguments. By convention, the instance is called |
| 804 | *self* but could be called *this* or any other variable name. |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 805 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 806 | Methods can be created manually with :class:`types.MethodType` which is |
| 807 | roughly equivalent to:: |
| 808 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 809 | class MethodType: |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 810 | "Emulate Py_MethodType in Objects/classobject.c" |
| 811 | |
| 812 | def __init__(self, func, obj): |
| 813 | self.__func__ = func |
| 814 | self.__self__ = obj |
| 815 | |
| 816 | def __call__(self, *args, **kwargs): |
| 817 | func = self.__func__ |
| 818 | obj = self.__self__ |
| 819 | return func(obj, *args, **kwargs) |
| 820 | |
| 821 | To support automatic creation of methods, functions include the |
| 822 | :meth:`__get__` method for binding methods during attribute access. This |
Raymond Hettinger | 8031877 | 2020-11-06 01:30:17 -0800 | [diff] [blame] | 823 | means that functions are non-data descriptors that return bound methods |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 824 | during dotted lookup from an instance. Here's how it works:: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 825 | |
Serhiy Storchaka | e042a45 | 2019-06-10 13:35:52 +0300 | [diff] [blame] | 826 | class Function: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 827 | ... |
| 828 | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 829 | def __get__(self, obj, objtype=None): |
| 830 | "Simulate func_descr_get() in Objects/funcobject.c" |
Raymond Hettinger | 0d4497b | 2017-09-25 01:05:49 -0700 | [diff] [blame] | 831 | if obj is None: |
| 832 | return self |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 833 | return MethodType(self, obj) |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 834 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 835 | Running the following class in the interpreter shows how the function |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 836 | descriptor works in practice:: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 837 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 838 | class D: |
| 839 | def f(self, x): |
| 840 | return x |
Raymond Hettinger | 0d4497b | 2017-09-25 01:05:49 -0700 | [diff] [blame] | 841 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 842 | The function has a :term:`qualified name` attribute to support introspection:: |
| 843 | |
| 844 | >>> D.f.__qualname__ |
| 845 | 'D.f' |
| 846 | |
| 847 | Accessing the function through the class dictionary does not invoke |
| 848 | :meth:`__get__`. Instead, it just returns the underlying function object:: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 849 | |
Raymond Hettinger | 0d4497b | 2017-09-25 01:05:49 -0700 | [diff] [blame] | 850 | >>> D.__dict__['f'] |
| 851 | <function D.f at 0x00C45070> |
| 852 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 853 | Dotted access from a class calls :meth:`__get__` which just returns the |
| 854 | underlying function unchanged:: |
| 855 | |
Raymond Hettinger | 0d4497b | 2017-09-25 01:05:49 -0700 | [diff] [blame] | 856 | >>> D.f |
| 857 | <function D.f at 0x00C45070> |
| 858 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 859 | The interesting behavior occurs during dotted access from an instance. The |
| 860 | dotted lookup calls :meth:`__get__` which returns a bound method object:: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 861 | |
| 862 | >>> d = D() |
Raymond Hettinger | 0d4497b | 2017-09-25 01:05:49 -0700 | [diff] [blame] | 863 | >>> d.f |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 864 | <bound method D.f of <__main__.D object at 0x00B18C90>> |
| 865 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 866 | Internally, the bound method stores the underlying function and the bound |
| 867 | instance:: |
| 868 | |
Raymond Hettinger | 0d4497b | 2017-09-25 01:05:49 -0700 | [diff] [blame] | 869 | >>> d.f.__func__ |
| 870 | <function D.f at 0x1012e5ae8> |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 871 | |
Raymond Hettinger | 0d4497b | 2017-09-25 01:05:49 -0700 | [diff] [blame] | 872 | >>> d.f.__self__ |
| 873 | <__main__.D object at 0x1012e1f98> |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 874 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 875 | If you have ever wondered where *self* comes from in regular methods or where |
| 876 | *cls* comes from in class methods, this is it! |
| 877 | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 878 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 879 | Static methods |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 880 | -------------- |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 881 | |
| 882 | Non-data descriptors provide a simple mechanism for variations on the usual |
| 883 | patterns of binding functions into methods. |
| 884 | |
| 885 | To recap, functions have a :meth:`__get__` method so that they can be converted |
Serhiy Storchaka | d65c949 | 2015-11-02 14:10:23 +0200 | [diff] [blame] | 886 | to a method when accessed as attributes. The non-data descriptor transforms an |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 887 | ``obj.f(*args)`` call into ``f(obj, *args)``. Calling ``cls.f(*args)`` |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 888 | becomes ``f(*args)``. |
| 889 | |
| 890 | This chart summarizes the binding and its two most useful variants: |
| 891 | |
| 892 | +-----------------+----------------------+------------------+ |
| 893 | | Transformation | Called from an | Called from a | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 894 | | | object | class | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 895 | +=================+======================+==================+ |
| 896 | | function | f(obj, \*args) | f(\*args) | |
| 897 | +-----------------+----------------------+------------------+ |
| 898 | | staticmethod | f(\*args) | f(\*args) | |
| 899 | +-----------------+----------------------+------------------+ |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 900 | | classmethod | f(type(obj), \*args) | f(cls, \*args) | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 901 | +-----------------+----------------------+------------------+ |
| 902 | |
| 903 | Static methods return the underlying function without changes. Calling either |
| 904 | ``c.f`` or ``C.f`` is the equivalent of a direct lookup into |
| 905 | ``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a |
| 906 | result, the function becomes identically accessible from either an object or a |
| 907 | class. |
| 908 | |
| 909 | Good candidates for static methods are methods that do not reference the |
| 910 | ``self`` variable. |
| 911 | |
| 912 | For instance, a statistics package may include a container class for |
| 913 | experimental data. The class provides normal methods for computing the average, |
| 914 | mean, median, and other descriptive statistics that depend on the data. However, |
| 915 | there may be useful functions which are conceptually related but do not depend |
| 916 | on the data. For instance, ``erf(x)`` is handy conversion routine that comes up |
| 917 | in statistical work but does not directly depend on a particular dataset. |
| 918 | It can be called either from an object or the class: ``s.erf(1.5) --> .9332`` or |
| 919 | ``Sample.erf(1.5) --> .9332``. |
| 920 | |
Raymond Hettinger | 4a9c637 | 2020-10-24 20:34:39 -0700 | [diff] [blame] | 921 | Since static methods return the underlying function with no changes, the |
| 922 | example calls are unexciting:: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 923 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 924 | class E: |
| 925 | @staticmethod |
| 926 | def f(x): |
| 927 | print(x) |
| 928 | |
Shubham Aggarwal | abbdd1f | 2019-03-20 08:25:55 +0530 | [diff] [blame] | 929 | >>> E.f(3) |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 930 | 3 |
Shubham Aggarwal | abbdd1f | 2019-03-20 08:25:55 +0530 | [diff] [blame] | 931 | >>> E().f(3) |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 932 | 3 |
| 933 | |
| 934 | Using the non-data descriptor protocol, a pure Python version of |
| 935 | :func:`staticmethod` would look like this:: |
| 936 | |
Serhiy Storchaka | e042a45 | 2019-06-10 13:35:52 +0300 | [diff] [blame] | 937 | class StaticMethod: |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 938 | "Emulate PyStaticMethod_Type() in Objects/funcobject.c" |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 939 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 940 | def __init__(self, f): |
| 941 | self.f = f |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 942 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 943 | def __get__(self, obj, objtype=None): |
| 944 | return self.f |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 945 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 946 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 947 | Class methods |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 948 | ------------- |
| 949 | |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 950 | Unlike static methods, class methods prepend the class reference to the |
| 951 | argument list before calling the function. This format is the same |
| 952 | for whether the caller is an object or a class:: |
| 953 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 954 | class F: |
| 955 | @classmethod |
| 956 | def f(cls, x): |
| 957 | return cls.__name__, x |
| 958 | |
| 959 | >>> print(F.f(3)) |
| 960 | ('F', 3) |
| 961 | >>> print(F().f(3)) |
| 962 | ('F', 3) |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 963 | |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 964 | This behavior is useful whenever the method only needs to have a class |
| 965 | reference and does rely on data stored in a specific instance. One use for |
| 966 | class methods is to create alternate class constructors. For example, the |
| 967 | classmethod :func:`dict.fromkeys` creates a new dictionary from a list of |
| 968 | keys. The pure Python equivalent is:: |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 969 | |
Serhiy Storchaka | e042a45 | 2019-06-10 13:35:52 +0300 | [diff] [blame] | 970 | class Dict: |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 971 | ... |
| 972 | |
| 973 | @classmethod |
| 974 | def fromkeys(cls, iterable, value=None): |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 975 | "Emulate dict_fromkeys() in Objects/dictobject.c" |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 976 | d = cls() |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 977 | for key in iterable: |
| 978 | d[key] = value |
| 979 | return d |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 980 | |
| 981 | Now a new dictionary of unique keys can be constructed like this:: |
| 982 | |
| 983 | >>> Dict.fromkeys('abracadabra') |
| 984 | {'a': None, 'r': None, 'b': None, 'c': None, 'd': None} |
| 985 | |
| 986 | Using the non-data descriptor protocol, a pure Python version of |
| 987 | :func:`classmethod` would look like this:: |
| 988 | |
Serhiy Storchaka | e042a45 | 2019-06-10 13:35:52 +0300 | [diff] [blame] | 989 | class ClassMethod: |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 990 | "Emulate PyClassMethod_Type() in Objects/funcobject.c" |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 991 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 992 | def __init__(self, f): |
| 993 | self.f = f |
Georg Brandl | 45cceeb | 2010-05-19 21:39:51 +0000 | [diff] [blame] | 994 | |
Raymond Hettinger | 8d3d731 | 2020-10-23 12:55:39 -0700 | [diff] [blame] | 995 | def __get__(self, obj, cls=None): |
| 996 | if cls is None: |
| 997 | cls = type(obj) |
Raymond Hettinger | 8e5b0fd | 2020-10-23 18:37:27 -0700 | [diff] [blame] | 998 | if hasattr(obj, '__get__'): |
| 999 | return self.f.__get__(cls) |
Raymond Hettinger | e6a7ea4 | 2020-10-25 07:12:50 -0700 | [diff] [blame] | 1000 | return MethodType(self.f, cls) |
Raymond Hettinger | 8e5b0fd | 2020-10-23 18:37:27 -0700 | [diff] [blame] | 1001 | |
| 1002 | The code path for ``hasattr(obj, '__get__')`` was added in Python 3.9 and |
| 1003 | makes it possible for :func:`classmethod` to support chained decorators. |
| 1004 | For example, a classmethod and property could be chained together:: |
| 1005 | |
| 1006 | class G: |
| 1007 | @classmethod |
| 1008 | @property |
| 1009 | def __doc__(cls): |
| 1010 | return f'A doc for {cls.__name__!r}' |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1011 | |
Raymond Hettinger | e9208f0 | 2020-11-01 20:15:50 -0800 | [diff] [blame] | 1012 | Member objects and __slots__ |
| 1013 | ---------------------------- |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1014 | |
| 1015 | When a class defines ``__slots__``, it replaces instance dictionaries with a |
| 1016 | fixed-length array of slot values. From a user point of view that has |
| 1017 | several effects: |
| 1018 | |
| 1019 | 1. Provides immediate detection of bugs due to misspelled attribute |
| 1020 | assignments. Only attribute names specified in ``__slots__`` are allowed:: |
| 1021 | |
| 1022 | class Vehicle: |
| 1023 | __slots__ = ('id_number', 'make', 'model') |
| 1024 | |
| 1025 | >>> auto = Vehicle() |
| 1026 | >>> auto.id_nubmer = 'VYE483814LQEX' |
| 1027 | Traceback (most recent call last): |
| 1028 | ... |
| 1029 | AttributeError: 'Vehicle' object has no attribute 'id_nubmer' |
| 1030 | |
| 1031 | 2. Helps create immutable objects where descriptors manage access to private |
| 1032 | attributes stored in ``__slots__``:: |
| 1033 | |
| 1034 | class Immutable: |
| 1035 | |
Raymond Hettinger | 8031877 | 2020-11-06 01:30:17 -0800 | [diff] [blame] | 1036 | __slots__ = ('_dept', '_name') # Replace the instance dictionary |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1037 | |
| 1038 | def __init__(self, dept, name): |
| 1039 | self._dept = dept # Store to private attribute |
| 1040 | self._name = name # Store to private attribute |
| 1041 | |
| 1042 | @property # Read-only descriptor |
| 1043 | def dept(self): |
| 1044 | return self._dept |
| 1045 | |
| 1046 | @property |
| 1047 | def name(self): # Read-only descriptor |
| 1048 | return self._name |
| 1049 | |
| 1050 | mark = Immutable('Botany', 'Mark Watney') # Create an immutable instance |
| 1051 | |
| 1052 | 3. Saves memory. On a 64-bit Linux build, an instance with two attributes |
| 1053 | takes 48 bytes with ``__slots__`` and 152 bytes without. This `flyweight |
| 1054 | design pattern <https://en.wikipedia.org/wiki/Flyweight_pattern>`_ likely only |
| 1055 | matters when a large number of instances are going to be created. |
| 1056 | |
| 1057 | 4. Blocks tools like :func:`functools.cached_property` which require an |
| 1058 | instance dictionary to function correctly:: |
| 1059 | |
| 1060 | from functools import cached_property |
| 1061 | |
| 1062 | class CP: |
| 1063 | __slots__ = () # Eliminates the instance dict |
| 1064 | |
| 1065 | @cached_property # Requires an instance dict |
| 1066 | def pi(self): |
| 1067 | return 4 * sum((-1.0)**n / (2.0*n + 1.0) |
| 1068 | for n in reversed(range(100_000))) |
| 1069 | |
| 1070 | >>> CP().pi |
| 1071 | Traceback (most recent call last): |
| 1072 | ... |
| 1073 | TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property. |
| 1074 | |
| 1075 | It's not possible to create an exact drop-in pure Python version of |
| 1076 | ``__slots__`` because it requires direct access to C structures and control |
| 1077 | over object memory allocation. However, we can build a mostly faithful |
| 1078 | simulation where the actual C structure for slots is emulated by a private |
| 1079 | ``_slotvalues`` list. Reads and writes to that private structure are managed |
| 1080 | by member descriptors:: |
| 1081 | |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1082 | null = object() |
| 1083 | |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1084 | class Member: |
| 1085 | |
| 1086 | def __init__(self, name, clsname, offset): |
| 1087 | 'Emulate PyMemberDef in Include/structmember.h' |
| 1088 | # Also see descr_new() in Objects/descrobject.c |
| 1089 | self.name = name |
| 1090 | self.clsname = clsname |
| 1091 | self.offset = offset |
| 1092 | |
| 1093 | def __get__(self, obj, objtype=None): |
| 1094 | 'Emulate member_get() in Objects/descrobject.c' |
| 1095 | # Also see PyMember_GetOne() in Python/structmember.c |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1096 | value = obj._slotvalues[self.offset] |
| 1097 | if value is null: |
| 1098 | raise AttributeError(self.name) |
| 1099 | return value |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1100 | |
| 1101 | def __set__(self, obj, value): |
| 1102 | 'Emulate member_set() in Objects/descrobject.c' |
| 1103 | obj._slotvalues[self.offset] = value |
| 1104 | |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1105 | def __delete__(self, obj): |
| 1106 | 'Emulate member_delete() in Objects/descrobject.c' |
| 1107 | value = obj._slotvalues[self.offset] |
| 1108 | if value is null: |
| 1109 | raise AttributeError(self.name) |
| 1110 | obj._slotvalues[self.offset] = null |
| 1111 | |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1112 | def __repr__(self): |
| 1113 | 'Emulate member_repr() in Objects/descrobject.c' |
| 1114 | return f'<Member {self.name!r} of {self.clsname!r}>' |
| 1115 | |
| 1116 | The :meth:`type.__new__` method takes care of adding member objects to class |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1117 | variables:: |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1118 | |
| 1119 | class Type(type): |
| 1120 | 'Simulate how the type metaclass adds member objects for slots' |
| 1121 | |
| 1122 | def __new__(mcls, clsname, bases, mapping): |
| 1123 | 'Emuluate type_new() in Objects/typeobject.c' |
| 1124 | # type_new() calls PyTypeReady() which calls add_methods() |
| 1125 | slot_names = mapping.get('slot_names', []) |
| 1126 | for offset, name in enumerate(slot_names): |
| 1127 | mapping[name] = Member(name, clsname, offset) |
| 1128 | return type.__new__(mcls, clsname, bases, mapping) |
| 1129 | |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1130 | The :meth:`object.__new__` method takes care of creating instances that have |
| 1131 | slots instead of an instance dictionary. Here is a rough simulation in pure |
| 1132 | Python:: |
| 1133 | |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1134 | class Object: |
| 1135 | 'Simulate how object.__new__() allocates memory for __slots__' |
| 1136 | |
| 1137 | def __new__(cls, *args): |
| 1138 | 'Emulate object_new() in Objects/typeobject.c' |
| 1139 | inst = super().__new__(cls) |
| 1140 | if hasattr(cls, 'slot_names'): |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1141 | empty_slots = [null] * len(cls.slot_names) |
| 1142 | object.__setattr__(inst, '_slotvalues', empty_slots) |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1143 | return inst |
| 1144 | |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1145 | def __setattr__(self, name, value): |
| 1146 | 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' |
| 1147 | cls = type(self) |
| 1148 | if hasattr(cls, 'slot_names') and name not in cls.slot_names: |
| 1149 | raise AttributeError( |
| 1150 | f'{type(self).__name__!r} object has no attribute {name!r}' |
| 1151 | ) |
| 1152 | super().__setattr__(name, value) |
| 1153 | |
| 1154 | def __delattr__(self, name): |
| 1155 | 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' |
| 1156 | cls = type(self) |
| 1157 | if hasattr(cls, 'slot_names') and name not in cls.slot_names: |
| 1158 | raise AttributeError( |
| 1159 | f'{type(self).__name__!r} object has no attribute {name!r}' |
| 1160 | ) |
| 1161 | super().__delattr__(name) |
| 1162 | |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1163 | To use the simulation in a real class, just inherit from :class:`Object` and |
| 1164 | set the :term:`metaclass` to :class:`Type`:: |
| 1165 | |
| 1166 | class H(Object, metaclass=Type): |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1167 | 'Instance variables stored in slots' |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1168 | |
| 1169 | slot_names = ['x', 'y'] |
| 1170 | |
| 1171 | def __init__(self, x, y): |
| 1172 | self.x = x |
| 1173 | self.y = y |
| 1174 | |
| 1175 | At this point, the metaclass has loaded member objects for *x* and *y*:: |
| 1176 | |
| 1177 | >>> import pprint |
| 1178 | >>> pprint.pp(dict(vars(H))) |
| 1179 | {'__module__': '__main__', |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1180 | '__doc__': 'Instance variables stored in slots', |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1181 | 'slot_names': ['x', 'y'], |
| 1182 | '__init__': <function H.__init__ at 0x7fb5d302f9d0>, |
| 1183 | 'x': <Member 'x' of 'H'>, |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1184 | 'y': <Member 'y' of 'H'>} |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1185 | |
| 1186 | When instances are created, they have a ``slot_values`` list where the |
| 1187 | attributes are stored:: |
| 1188 | |
| 1189 | >>> h = H(10, 20) |
| 1190 | >>> vars(h) |
| 1191 | {'_slotvalues': [10, 20]} |
| 1192 | >>> h.x = 55 |
| 1193 | >>> vars(h) |
| 1194 | {'_slotvalues': [55, 20]} |
| 1195 | |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1196 | Misspelled or unassigned attributes will raise an exception:: |
Raymond Hettinger | 74fa464 | 2020-11-01 18:02:37 -0800 | [diff] [blame] | 1197 | |
Raymond Hettinger | ffae932 | 2020-11-23 10:56:59 -0800 | [diff] [blame^] | 1198 | >>> h.xz |
| 1199 | Traceback (most recent call last): |
| 1200 | ... |
| 1201 | AttributeError: 'H' object has no attribute 'xz' |