diff options
Diffstat (limited to 'devdocs/python~3.12/howto%2Fdescriptor.html')
| -rw-r--r-- | devdocs/python~3.12/howto%2Fdescriptor.html | 631 |
1 files changed, 631 insertions, 0 deletions
diff --git a/devdocs/python~3.12/howto%2Fdescriptor.html b/devdocs/python~3.12/howto%2Fdescriptor.html new file mode 100644 index 00000000..94257f03 --- /dev/null +++ b/devdocs/python~3.12/howto%2Fdescriptor.html @@ -0,0 +1,631 @@ + <span id="descriptorhowto"></span><h1>Descriptor HowTo Guide</h1> <dl class="field-list simple"> <dt class="field-odd">Author</dt> <dd class="field-odd"> +<p>Raymond Hettinger</p> </dd> <dt class="field-even">Contact</dt> <dd class="field-even"> +<p><python at rcn dot com></p> </dd> </dl> <ul> <li> +<p><a class="reference internal" href="#primer" id="id2">Primer</a></p> <ul> <li><a class="reference internal" href="#simple-example-a-descriptor-that-returns-a-constant" id="id3">Simple example: A descriptor that returns a constant</a></li> <li><a class="reference internal" href="#dynamic-lookups" id="id4">Dynamic lookups</a></li> <li><a class="reference internal" href="#managed-attributes" id="id5">Managed attributes</a></li> <li><a class="reference internal" href="#customized-names" id="id6">Customized names</a></li> <li><a class="reference internal" href="#closing-thoughts" id="id7">Closing thoughts</a></li> </ul> </li> <li> +<p><a class="reference internal" href="#complete-practical-example" id="id8">Complete Practical Example</a></p> <ul> <li><a class="reference internal" href="#validator-class" id="id9">Validator class</a></li> <li><a class="reference internal" href="#custom-validators" id="id10">Custom validators</a></li> <li><a class="reference internal" href="#practical-application" id="id11">Practical application</a></li> </ul> </li> <li> +<p><a class="reference internal" href="#technical-tutorial" id="id12">Technical Tutorial</a></p> <ul> <li><a class="reference internal" href="#abstract" id="id13">Abstract</a></li> <li><a class="reference internal" href="#definition-and-introduction" id="id14">Definition and introduction</a></li> <li><a class="reference internal" href="#descriptor-protocol" id="id15">Descriptor protocol</a></li> <li><a class="reference internal" href="#overview-of-descriptor-invocation" id="id16">Overview of descriptor invocation</a></li> <li><a class="reference internal" href="#invocation-from-an-instance" id="id17">Invocation from an instance</a></li> <li><a class="reference internal" href="#invocation-from-a-class" id="id18">Invocation from a class</a></li> <li><a class="reference internal" href="#invocation-from-super" id="id19">Invocation from super</a></li> <li><a class="reference internal" href="#summary-of-invocation-logic" id="id20">Summary of invocation logic</a></li> <li><a class="reference internal" href="#automatic-name-notification" id="id21">Automatic name notification</a></li> <li><a class="reference internal" href="#orm-example" id="id22">ORM example</a></li> </ul> </li> <li> +<p><a class="reference internal" href="#pure-python-equivalents" id="id23">Pure Python Equivalents</a></p> <ul> <li><a class="reference internal" href="#properties" id="id24">Properties</a></li> <li><a class="reference internal" href="#functions-and-methods" id="id25">Functions and methods</a></li> <li><a class="reference internal" href="#kinds-of-methods" id="id26">Kinds of methods</a></li> <li><a class="reference internal" href="#static-methods" id="id27">Static methods</a></li> <li><a class="reference internal" href="#class-methods" id="id28">Class methods</a></li> <li><a class="reference internal" href="#member-objects-and-slots" id="id29">Member objects and __slots__</a></li> </ul> </li> </ul> +<ul class="simple"> </ul> <p><a class="reference internal" href="../glossary#term-descriptor"><span class="xref std std-term">Descriptors</span></a> let objects customize attribute lookup, storage, and deletion.</p> <p>This guide has four major sections:</p> <ol class="arabic simple"> <li>The “primer” gives a basic overview, moving gently from simple examples, adding one feature at a time. Start here if you’re new to descriptors.</li> <li>The second section shows a complete, practical descriptor example. If you already know the basics, start there.</li> <li>The third section provides a more technical tutorial that goes into the detailed mechanics of how descriptors work. Most people don’t need this level of detail.</li> <li>The last section has pure Python equivalents for built-in descriptors that are written in C. Read this if you’re curious about how functions turn into bound methods or about the implementation of common tools like <a class="reference internal" href="../library/functions#classmethod" title="classmethod"><code>classmethod()</code></a>, <a class="reference internal" href="../library/functions#staticmethod" title="staticmethod"><code>staticmethod()</code></a>, <a class="reference internal" href="../library/functions#property" title="property"><code>property()</code></a>, and <a class="reference internal" href="../glossary#term-__slots__"><span class="xref std std-term">__slots__</span></a>.</li> </ol> <section id="primer"> <h2>Primer</h2> <p>In this primer, we start with the most basic possible example and then we’ll add new capabilities one by one.</p> <section id="simple-example-a-descriptor-that-returns-a-constant"> <h3>Simple example: A descriptor that returns a constant</h3> <p>The <code>Ten</code> class is a descriptor whose <code>__get__()</code> method always returns the constant <code>10</code>:</p> <pre data-language="python">class Ten: + def __get__(self, obj, objtype=None): + return 10 +</pre> <p>To use the descriptor, it must be stored as a class variable in another class:</p> <pre data-language="python">class A: + x = 5 # Regular class attribute + y = Ten() # Descriptor instance +</pre> <p>An interactive session shows the difference between normal attribute lookup and descriptor lookup:</p> <pre data-language="pycon3">>>> a = A() # Make an instance of class A +>>> a.x # Normal attribute lookup +5 +>>> a.y # Descriptor lookup +10 +</pre> <p>In the <code>a.x</code> attribute lookup, the dot operator finds <code>'x': 5</code> in the class dictionary. In the <code>a.y</code> lookup, the dot operator finds a descriptor instance, recognized by its <code>__get__</code> method. Calling that method returns <code>10</code>.</p> <p>Note that the value <code>10</code> is not stored in either the class dictionary or the instance dictionary. Instead, the value <code>10</code> is computed on demand.</p> <p>This example shows how a simple descriptor works, but it isn’t very useful. For retrieving constants, normal attribute lookup would be better.</p> <p>In the next section, we’ll create something more useful, a dynamic lookup.</p> </section> <section id="dynamic-lookups"> <h3>Dynamic lookups</h3> <p>Interesting descriptors typically run computations instead of returning constants:</p> <pre data-language="python">import os + +class DirectorySize: + + def __get__(self, obj, objtype=None): + return len(os.listdir(obj.dirname)) + +class Directory: + + size = DirectorySize() # Descriptor instance + + def __init__(self, dirname): + self.dirname = dirname # Regular instance attribute +</pre> <p>An interactive session shows that the lookup is dynamic — it computes different, updated answers each time:</p> <pre data-language="python">>>> s = Directory('songs') +>>> g = Directory('games') +>>> s.size # The songs directory has twenty files +20 +>>> g.size # The games directory has three files +3 +>>> os.remove('games/chess') # Delete a game +>>> g.size # File count is automatically updated +2 +</pre> <p>Besides showing how descriptors can run computations, this example also reveals the purpose of the parameters to <code>__get__()</code>. The <em>self</em> parameter is <em>size</em>, an instance of <em>DirectorySize</em>. The <em>obj</em> parameter is either <em>g</em> or <em>s</em>, an instance of <em>Directory</em>. It is the <em>obj</em> parameter that lets the <code>__get__()</code> method learn the target directory. The <em>objtype</em> parameter is the class <em>Directory</em>.</p> </section> <section id="managed-attributes"> <h3>Managed attributes</h3> <p>A popular use for descriptors is managing access to instance data. The descriptor is assigned to a public attribute in the class dictionary while the actual data is stored as a private attribute in the instance dictionary. The descriptor’s <code>__get__()</code> and <code>__set__()</code> methods are triggered when the public attribute is accessed.</p> <p>In the following example, <em>age</em> is the public attribute and <em>_age</em> is the private attribute. When the public attribute is accessed, the descriptor logs the lookup or update:</p> <pre data-language="python">import logging + +logging.basicConfig(level=logging.INFO) + +class LoggedAgeAccess: + + def __get__(self, obj, objtype=None): + value = obj._age + logging.info('Accessing %r giving %r', 'age', value) + return value + + def __set__(self, obj, value): + logging.info('Updating %r to %r', 'age', value) + obj._age = value + +class Person: + + age = LoggedAgeAccess() # Descriptor instance + + def __init__(self, name, age): + self.name = name # Regular instance attribute + self.age = age # Calls __set__() + + def birthday(self): + self.age += 1 # Calls both __get__() and __set__() +</pre> <p>An interactive session shows that all access to the managed attribute <em>age</em> is logged, but that the regular attribute <em>name</em> is not logged:</p> <pre data-language="pycon3">>>> mary = Person('Mary M', 30) # The initial age update is logged +INFO:root:Updating 'age' to 30 +>>> dave = Person('David D', 40) +INFO:root:Updating 'age' to 40 + +>>> vars(mary) # The actual data is in a private attribute +{'name': 'Mary M', '_age': 30} +>>> vars(dave) +{'name': 'David D', '_age': 40} + +>>> mary.age # Access the data and log the lookup +INFO:root:Accessing 'age' giving 30 +30 +>>> mary.birthday() # Updates are logged as well +INFO:root:Accessing 'age' giving 30 +INFO:root:Updating 'age' to 31 + +>>> dave.name # Regular attribute lookup isn't logged +'David D' +>>> dave.age # Only the managed attribute is logged +INFO:root:Accessing 'age' giving 40 +40 +</pre> <p>One major issue with this example is that the private name <em>_age</em> is hardwired in the <em>LoggedAgeAccess</em> class. That means that each instance can only have one logged attribute and that its name is unchangeable. In the next example, we’ll fix that problem.</p> </section> <section id="customized-names"> <h3>Customized names</h3> <p>When a class uses descriptors, it can inform each descriptor about which variable name was used.</p> <p>In this example, the <code>Person</code> class has two descriptor instances, <em>name</em> and <em>age</em>. When the <code>Person</code> class is defined, it makes a callback to <code>__set_name__()</code> in <em>LoggedAccess</em> so that the field names can be recorded, giving each descriptor its own <em>public_name</em> and <em>private_name</em>:</p> <pre data-language="python">import logging + +logging.basicConfig(level=logging.INFO) + +class LoggedAccess: + + def __set_name__(self, owner, name): + self.public_name = name + self.private_name = '_' + name + + def __get__(self, obj, objtype=None): + value = getattr(obj, self.private_name) + logging.info('Accessing %r giving %r', self.public_name, value) + return value + + def __set__(self, obj, value): + logging.info('Updating %r to %r', self.public_name, value) + setattr(obj, self.private_name, value) + +class Person: + + name = LoggedAccess() # First descriptor instance + age = LoggedAccess() # Second descriptor instance + + def __init__(self, name, age): + self.name = name # Calls the first descriptor + self.age = age # Calls the second descriptor + + def birthday(self): + self.age += 1 +</pre> <p>An interactive session shows that the <code>Person</code> class has called <code>__set_name__()</code> so that the field names would be recorded. Here we call <a class="reference internal" href="../library/functions#vars" title="vars"><code>vars()</code></a> to look up the descriptor without triggering it:</p> <pre data-language="pycon3">>>> vars(vars(Person)['name']) +{'public_name': 'name', 'private_name': '_name'} +>>> vars(vars(Person)['age']) +{'public_name': 'age', 'private_name': '_age'} +</pre> <p>The new class now logs access to both <em>name</em> and <em>age</em>:</p> <pre data-language="pycon3">>>> pete = Person('Peter P', 10) +INFO:root:Updating 'name' to 'Peter P' +INFO:root:Updating 'age' to 10 +>>> kate = Person('Catherine C', 20) +INFO:root:Updating 'name' to 'Catherine C' +INFO:root:Updating 'age' to 20 +</pre> <p>The two <em>Person</em> instances contain only the private names:</p> <pre data-language="pycon3">>>> vars(pete) +{'_name': 'Peter P', '_age': 10} +>>> vars(kate) +{'_name': 'Catherine C', '_age': 20} +</pre> </section> <section id="closing-thoughts"> <h3>Closing thoughts</h3> <p>A <a class="reference internal" href="../glossary#term-descriptor"><span class="xref std std-term">descriptor</span></a> is what we call any object that defines <code>__get__()</code>, <code>__set__()</code>, or <code>__delete__()</code>.</p> <p>Optionally, descriptors can have a <code>__set_name__()</code> method. This is only used in cases where a descriptor needs to know either the class where it was created or the name of class variable it was assigned to. (This method, if present, is called even if the class is not a descriptor.)</p> <p>Descriptors get invoked by the dot operator during attribute lookup. If a descriptor is accessed indirectly with <code>vars(some_class)[descriptor_name]</code>, the descriptor instance is returned without invoking it.</p> <p>Descriptors only work when used as class variables. When put in instances, they have no effect.</p> <p>The main motivation for descriptors is to provide a hook allowing objects stored in class variables to control what happens during attribute lookup.</p> <p>Traditionally, the calling class controls what happens during lookup. Descriptors invert that relationship and allow the data being looked-up to have a say in the matter.</p> <p>Descriptors are used throughout the language. It is how functions turn into bound methods. Common tools like <a class="reference internal" href="../library/functions#classmethod" title="classmethod"><code>classmethod()</code></a>, <a class="reference internal" href="../library/functions#staticmethod" title="staticmethod"><code>staticmethod()</code></a>, <a class="reference internal" href="../library/functions#property" title="property"><code>property()</code></a>, and <a class="reference internal" href="../library/functools#functools.cached_property" title="functools.cached_property"><code>functools.cached_property()</code></a> are all implemented as descriptors.</p> </section> </section> <section id="complete-practical-example"> <h2>Complete Practical Example</h2> <p>In this example, we create a practical and powerful tool for locating notoriously hard to find data corruption bugs.</p> <section id="validator-class"> <h3>Validator class</h3> <p>A validator is a descriptor for managed attribute access. Prior to storing any data, it verifies that the new value meets various type and range restrictions. If those restrictions aren’t met, it raises an exception to prevent data corruption at its source.</p> <p>This <code>Validator</code> class is both an <a class="reference internal" href="../glossary#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a> and a managed attribute descriptor:</p> <pre data-language="python">from abc import ABC, abstractmethod + +class Validator(ABC): + + def __set_name__(self, owner, name): + self.private_name = '_' + name + + def __get__(self, obj, objtype=None): + return getattr(obj, self.private_name) + + def __set__(self, obj, value): + self.validate(value) + setattr(obj, self.private_name, value) + + @abstractmethod + def validate(self, value): + pass +</pre> <p>Custom validators need to inherit from <code>Validator</code> and must supply a <code>validate()</code> method to test various restrictions as needed.</p> </section> <section id="custom-validators"> <h3>Custom validators</h3> <p>Here are three practical data validation utilities:</p> <ol class="arabic simple"> <li> +<code>OneOf</code> verifies that a value is one of a restricted set of options.</li> <li> +<code>Number</code> verifies that a value is either an <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a> or <a class="reference internal" href="../library/functions#float" title="float"><code>float</code></a>. Optionally, it verifies that a value is between a given minimum or maximum.</li> <li> +<code>String</code> verifies that a value is a <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a>. Optionally, it validates a given minimum or maximum length. It can validate a user-defined <a class="reference external" href="https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)">predicate</a> as well.</li> </ol> <pre data-language="python">class OneOf(Validator): + + def __init__(self, *options): + self.options = set(options) + + def validate(self, value): + if value not in self.options: + raise ValueError(f'Expected {value!r} to be one of {self.options!r}') + +class Number(Validator): + + def __init__(self, minvalue=None, maxvalue=None): + self.minvalue = minvalue + self.maxvalue = maxvalue + + def validate(self, value): + if not isinstance(value, (int, float)): + raise TypeError(f'Expected {value!r} to be an int or float') + if self.minvalue is not None and value < self.minvalue: + raise ValueError( + f'Expected {value!r} to be at least {self.minvalue!r}' + ) + if self.maxvalue is not None and value > self.maxvalue: + raise ValueError( + f'Expected {value!r} to be no more than {self.maxvalue!r}' + ) + +class String(Validator): + + def __init__(self, minsize=None, maxsize=None, predicate=None): + self.minsize = minsize + self.maxsize = maxsize + self.predicate = predicate + + def validate(self, value): + if not isinstance(value, str): + raise TypeError(f'Expected {value!r} to be an str') + if self.minsize is not None and len(value) < self.minsize: + raise ValueError( + f'Expected {value!r} to be no smaller than {self.minsize!r}' + ) + if self.maxsize is not None and len(value) > self.maxsize: + raise ValueError( + f'Expected {value!r} to be no bigger than {self.maxsize!r}' + ) + if self.predicate is not None and not self.predicate(value): + raise ValueError( + f'Expected {self.predicate} to be true for {value!r}' + ) +</pre> </section> <section id="practical-application"> <h3>Practical application</h3> <p>Here’s how the data validators can be used in a real class:</p> <pre data-language="python">class Component: + + name = String(minsize=3, maxsize=10, predicate=str.isupper) + kind = OneOf('wood', 'metal', 'plastic') + quantity = Number(minvalue=0) + + def __init__(self, name, kind, quantity): + self.name = name + self.kind = kind + self.quantity = quantity +</pre> <p>The descriptors prevent invalid instances from being created:</p> <pre data-language="pycon3">>>> Component('Widget', 'metal', 5) # Blocked: 'Widget' is not all uppercase +Traceback (most recent call last): + ... +ValueError: Expected <method 'isupper' of 'str' objects> to be true for 'Widget' + +>>> Component('WIDGET', 'metle', 5) # Blocked: 'metle' is misspelled +Traceback (most recent call last): + ... +ValueError: Expected 'metle' to be one of {'metal', 'plastic', 'wood'} + +>>> Component('WIDGET', 'metal', -5) # Blocked: -5 is negative +Traceback (most recent call last): + ... +ValueError: Expected -5 to be at least 0 +>>> Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number +Traceback (most recent call last): + ... +TypeError: Expected 'V' to be an int or float + +>>> c = Component('WIDGET', 'metal', 5) # Allowed: The inputs are valid +</pre> </section> </section> <section id="technical-tutorial"> <h2>Technical Tutorial</h2> <p>What follows is a more technical tutorial for the mechanics and details of how descriptors work.</p> <section id="abstract"> <h3>Abstract</h3> <p>Defines descriptors, summarizes the protocol, and shows how descriptors are called. Provides an example showing how object relational mappings work.</p> <p>Learning about descriptors not only provides access to a larger toolset, it creates a deeper understanding of how Python works.</p> </section> <section id="definition-and-introduction"> <h3>Definition and introduction</h3> <p>In general, a descriptor is an attribute value that has one of the methods in the descriptor protocol. Those methods are <code>__get__()</code>, <code>__set__()</code>, and <code>__delete__()</code>. If any of those methods are defined for an attribute, it is said to be a <a class="reference internal" href="../glossary#term-descriptor"><span class="xref std std-term">descriptor</span></a>.</p> <p>The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, <code>a.x</code> has a lookup chain starting with <code>a.__dict__['x']</code>, then <code>type(a).__dict__['x']</code>, and continuing through the method resolution order of <code>type(a)</code>. If the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined.</p> <p>Descriptors are a powerful, general purpose protocol. They are the mechanism behind properties, methods, static methods, class methods, and <a class="reference internal" href="../library/functions#super" title="super"><code>super()</code></a>. They are used throughout Python itself. Descriptors simplify the underlying C code and offer a flexible set of new tools for everyday Python programs.</p> </section> <section id="descriptor-protocol"> <h3>Descriptor protocol</h3> <p><code>descr.__get__(self, obj, type=None)</code></p> <p><code>descr.__set__(self, obj, value)</code></p> <p><code>descr.__delete__(self, obj)</code></p> <p>That is all there is to it. Define any of these methods and an object is considered a descriptor and can override default behavior upon being looked up as an attribute.</p> <p>If an object defines <code>__set__()</code> or <code>__delete__()</code>, it is considered a data descriptor. Descriptors that only define <code>__get__()</code> are called non-data descriptors (they are often used for methods but other uses are possible).</p> <p>Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.</p> <p>To make a read-only data descriptor, define both <code>__get__()</code> and <code>__set__()</code> with the <code>__set__()</code> raising an <a class="reference internal" href="../library/exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> when called. Defining the <code>__set__()</code> method with an exception raising placeholder is enough to make it a data descriptor.</p> </section> <section id="overview-of-descriptor-invocation"> <h3>Overview of descriptor invocation</h3> <p>A descriptor can be called directly with <code>desc.__get__(obj)</code> or <code>desc.__get__(None, cls)</code>.</p> <p>But it is more common for a descriptor to be invoked automatically from attribute access.</p> <p>The expression <code>obj.x</code> looks up the attribute <code>x</code> in the chain of namespaces for <code>obj</code>. If the search finds a descriptor outside of the instance <code>__dict__</code>, its <code>__get__()</code> method is invoked according to the precedence rules listed below.</p> <p>The details of invocation depend on whether <code>obj</code> is an object, class, or instance of super.</p> </section> <section id="invocation-from-an-instance"> <h3>Invocation from an instance</h3> <p>Instance lookup scans through a chain of namespaces giving data descriptors the highest priority, followed by instance variables, then non-data descriptors, then class variables, and lastly <code>__getattr__()</code> if it is provided.</p> <p>If a descriptor is found for <code>a.x</code>, then it is invoked with: <code>desc.__get__(a, type(a))</code>.</p> <p>The logic for a dotted lookup is in <a class="reference internal" href="../reference/datamodel#object.__getattribute__" title="object.__getattribute__"><code>object.__getattribute__()</code></a>. Here is a pure Python equivalent:</p> <pre data-language="python">def find_name_in_mro(cls, name, default): + "Emulate _PyType_Lookup() in Objects/typeobject.c" + for base in cls.__mro__: + if name in vars(base): + return vars(base)[name] + return default + +def object_getattribute(obj, name): + "Emulate PyObject_GenericGetAttr() in Objects/object.c" + null = object() + objtype = type(obj) + cls_var = find_name_in_mro(objtype, name, null) + descr_get = getattr(type(cls_var), '__get__', null) + if descr_get is not null: + if (hasattr(type(cls_var), '__set__') + or hasattr(type(cls_var), '__delete__')): + return descr_get(cls_var, obj, objtype) # data descriptor + if hasattr(obj, '__dict__') and name in vars(obj): + return vars(obj)[name] # instance variable + if descr_get is not null: + return descr_get(cls_var, obj, objtype) # non-data descriptor + if cls_var is not null: + return cls_var # class variable + raise AttributeError(name) +</pre> <p>Note, there is no <code>__getattr__()</code> hook in the <code>__getattribute__()</code> code. That is why calling <code>__getattribute__()</code> directly or with <code>super().__getattribute__</code> will bypass <code>__getattr__()</code> entirely.</p> <p>Instead, it is the dot operator and the <a class="reference internal" href="../library/functions#getattr" title="getattr"><code>getattr()</code></a> function that are responsible for invoking <code>__getattr__()</code> whenever <code>__getattribute__()</code> raises an <a class="reference internal" href="../library/exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a>. Their logic is encapsulated in a helper function:</p> <pre data-language="python">def getattr_hook(obj, name): + "Emulate slot_tp_getattr_hook() in Objects/typeobject.c" + try: + return obj.__getattribute__(name) + except AttributeError: + if not hasattr(type(obj), '__getattr__'): + raise + return type(obj).__getattr__(obj, name) # __getattr__ +</pre> </section> <section id="invocation-from-a-class"> <h3>Invocation from a class</h3> <p>The logic for a dotted lookup such as <code>A.x</code> is in <code>type.__getattribute__()</code>. The steps are similar to those for <a class="reference internal" href="../reference/datamodel#object.__getattribute__" title="object.__getattribute__"><code>object.__getattribute__()</code></a> but the instance dictionary lookup is replaced by a search through the class’s <a class="reference internal" href="../glossary#term-method-resolution-order"><span class="xref std std-term">method resolution order</span></a>.</p> <p>If a descriptor is found, it is invoked with <code>desc.__get__(None, A)</code>.</p> <p>The full C implementation can be found in <code>type_getattro()</code> and <code>_PyType_Lookup()</code> in <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Objects/typeobject.c">Objects/typeobject.c</a>.</p> </section> <section id="invocation-from-super"> <h3>Invocation from super</h3> <p>The logic for super’s dotted lookup is in the <code>__getattribute__()</code> method for object returned by <a class="reference internal" href="../library/functions#super" title="super"><code>super()</code></a>.</p> <p>A dotted lookup such as <code>super(A, obj).m</code> searches <code>obj.__class__.__mro__</code> for the base class <code>B</code> immediately following <code>A</code> and then returns <code>B.__dict__['m'].__get__(obj, A)</code>. If not a descriptor, <code>m</code> is returned unchanged.</p> <p>The full C implementation can be found in <code>super_getattro()</code> in <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Objects/typeobject.c">Objects/typeobject.c</a>. A pure Python equivalent can be found in <a class="reference external" href="https://www.python.org/download/releases/2.2.3/descrintro/#cooperation">Guido’s Tutorial</a>.</p> </section> <section id="summary-of-invocation-logic"> <h3>Summary of invocation logic</h3> <p>The mechanism for descriptors is embedded in the <code>__getattribute__()</code> methods for <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a>, <a class="reference internal" href="../library/functions#type" title="type"><code>type</code></a>, and <a class="reference internal" href="../library/functions#super" title="super"><code>super()</code></a>.</p> <p>The important points to remember are:</p> <ul class="simple"> <li>Descriptors are invoked by the <code>__getattribute__()</code> method.</li> <li>Classes inherit this machinery from <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a>, <a class="reference internal" href="../library/functions#type" title="type"><code>type</code></a>, or <a class="reference internal" href="../library/functions#super" title="super"><code>super()</code></a>.</li> <li>Overriding <code>__getattribute__()</code> prevents automatic descriptor calls because all the descriptor logic is in that method.</li> <li> +<a class="reference internal" href="../reference/datamodel#object.__getattribute__" title="object.__getattribute__"><code>object.__getattribute__()</code></a> and <code>type.__getattribute__()</code> make different calls to <code>__get__()</code>. The first includes the instance and may include the class. The second puts in <code>None</code> for the instance and always includes the class.</li> <li>Data descriptors always override instance dictionaries.</li> <li>Non-data descriptors may be overridden by instance dictionaries.</li> </ul> </section> <section id="automatic-name-notification"> <h3>Automatic name notification</h3> <p>Sometimes it is desirable for a descriptor to know what class variable name it was assigned to. When a new class is created, the <a class="reference internal" href="../library/functions#type" title="type"><code>type</code></a> metaclass scans the dictionary of the new class. If any of the entries are descriptors and if they define <code>__set_name__()</code>, that method is called with two arguments. The <em>owner</em> is the class where the descriptor is used, and the <em>name</em> is the class variable the descriptor was assigned to.</p> <p>The implementation details are in <code>type_new()</code> and <code>set_names()</code> in <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Objects/typeobject.c">Objects/typeobject.c</a>.</p> <p>Since the update logic is in <code>type.__new__()</code>, notifications only take place at the time of class creation. If descriptors are added to the class afterwards, <code>__set_name__()</code> will need to be called manually.</p> </section> <section id="orm-example"> <h3>ORM example</h3> <p>The following code is a simplified skeleton showing how data descriptors could be used to implement an <a class="reference external" href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping">object relational mapping</a>.</p> <p>The essential idea is that the data is stored in an external database. The Python instances only hold keys to the database’s tables. Descriptors take care of lookups or updates:</p> <pre data-language="python">class Field: + + def __set_name__(self, owner, name): + self.fetch = f'SELECT {name} FROM {owner.table} WHERE {owner.key}=?;' + self.store = f'UPDATE {owner.table} SET {name}=? WHERE {owner.key}=?;' + + def __get__(self, obj, objtype=None): + return conn.execute(self.fetch, [obj.key]).fetchone()[0] + + def __set__(self, obj, value): + conn.execute(self.store, [value, obj.key]) + conn.commit() +</pre> <p>We can use the <code>Field</code> class to define <a class="reference external" href="https://en.wikipedia.org/wiki/Database_model">models</a> that describe the schema for each table in a database:</p> <pre data-language="python">class Movie: + table = 'Movies' # Table name + key = 'title' # Primary key + director = Field() + year = Field() + + def __init__(self, key): + self.key = key + +class Song: + table = 'Music' + key = 'title' + artist = Field() + year = Field() + genre = Field() + + def __init__(self, key): + self.key = key +</pre> <p>To use the models, first connect to the database:</p> <pre data-language="python">>>> import sqlite3 +>>> conn = sqlite3.connect('entertainment.db') +</pre> <p>An interactive session shows how data is retrieved from the database and how it can be updated:</p> <pre data-language="pycon3">>>> Movie('Star Wars').director +'George Lucas' +>>> jaws = Movie('Jaws') +>>> f'Released in {jaws.year} by {jaws.director}' +'Released in 1975 by Steven Spielberg' + +>>> Song('Country Roads').artist +'John Denver' + +>>> Movie('Star Wars').director = 'J.J. Abrams' +>>> Movie('Star Wars').director +'J.J. Abrams' +</pre> </section> </section> <section id="pure-python-equivalents"> <h2>Pure Python Equivalents</h2> <p>The descriptor protocol is simple and offers exciting possibilities. Several use cases are so common that they have been prepackaged into built-in tools. Properties, bound methods, static methods, class methods, and __slots__ are all based on the descriptor protocol.</p> <section id="properties"> <h3>Properties</h3> <p>Calling <a class="reference internal" href="../library/functions#property" title="property"><code>property()</code></a> is a succinct way of building a data descriptor that triggers a function call upon access to an attribute. Its signature is:</p> <pre data-language="python">property(fget=None, fset=None, fdel=None, doc=None) -> property +</pre> <p>The documentation shows a typical use to define a managed attribute <code>x</code>:</p> <pre data-language="python">class C: + def getx(self): return self.__x + def setx(self, value): self.__x = value + def delx(self): del self.__x + x = property(getx, setx, delx, "I'm the 'x' property.") +</pre> <p>To see how <a class="reference internal" href="../library/functions#property" title="property"><code>property()</code></a> is implemented in terms of the descriptor protocol, here is a pure Python equivalent:</p> <pre data-language="python">class Property: + "Emulate PyProperty_Type() in Objects/descrobject.c" + + def __init__(self, fget=None, fset=None, fdel=None, doc=None): + self.fget = fget + self.fset = fset + self.fdel = fdel + if doc is None and fget is not None: + doc = fget.__doc__ + self.__doc__ = doc + self._name = '' + + def __set_name__(self, owner, name): + self._name = name + + def __get__(self, obj, objtype=None): + if obj is None: + return self + if self.fget is None: + raise AttributeError( + f'property {self._name!r} of {type(obj).__name__!r} object has no getter' + ) + return self.fget(obj) + + def __set__(self, obj, value): + if self.fset is None: + raise AttributeError( + f'property {self._name!r} of {type(obj).__name__!r} object has no setter' + ) + self.fset(obj, value) + + def __delete__(self, obj): + if self.fdel is None: + raise AttributeError( + f'property {self._name!r} of {type(obj).__name__!r} object has no deleter' + ) + self.fdel(obj) + + def getter(self, fget): + prop = type(self)(fget, self.fset, self.fdel, self.__doc__) + prop._name = self._name + return prop + + def setter(self, fset): + prop = type(self)(self.fget, fset, self.fdel, self.__doc__) + prop._name = self._name + return prop + + def deleter(self, fdel): + prop = type(self)(self.fget, self.fset, fdel, self.__doc__) + prop._name = self._name + return prop +</pre> <p>The <a class="reference internal" href="../library/functions#property" title="property"><code>property()</code></a> builtin helps whenever a user interface has granted attribute access and then subsequent changes require the intervention of a method.</p> <p>For instance, a spreadsheet class may grant access to a cell value through <code>Cell('b10').value</code>. Subsequent improvements to the program require the cell to be recalculated on every access; however, the programmer does not want to affect existing client code accessing the attribute directly. The solution is to wrap access to the value attribute in a property data descriptor:</p> <pre data-language="python">class Cell: + ... + + @property + def value(self): + "Recalculate the cell before returning value" + self.recalc() + return self._value +</pre> <p>Either the built-in <a class="reference internal" href="../library/functions#property" title="property"><code>property()</code></a> or our <code>Property()</code> equivalent would work in this example.</p> </section> <section id="functions-and-methods"> <h3>Functions and methods</h3> <p>Python’s object oriented features are built upon a function based environment. Using non-data descriptors, the two are merged seamlessly.</p> <p>Functions stored in class dictionaries get turned into methods when invoked. Methods only differ from regular functions in that the object instance is prepended to the other arguments. By convention, the instance is called <em>self</em> but could be called <em>this</em> or any other variable name.</p> <p>Methods can be created manually with <a class="reference internal" href="../library/types#types.MethodType" title="types.MethodType"><code>types.MethodType</code></a> which is roughly equivalent to:</p> <pre data-language="python">class MethodType: + "Emulate PyMethod_Type in Objects/classobject.c" + + def __init__(self, func, obj): + self.__func__ = func + self.__self__ = obj + + def __call__(self, *args, **kwargs): + func = self.__func__ + obj = self.__self__ + return func(obj, *args, **kwargs) +</pre> <p>To support automatic creation of methods, functions include the <code>__get__()</code> method for binding methods during attribute access. This means that functions are non-data descriptors that return bound methods during dotted lookup from an instance. Here’s how it works:</p> <pre data-language="python">class Function: + ... + + def __get__(self, obj, objtype=None): + "Simulate func_descr_get() in Objects/funcobject.c" + if obj is None: + return self + return MethodType(self, obj) +</pre> <p>Running the following class in the interpreter shows how the function descriptor works in practice:</p> <pre data-language="python">class D: + def f(self, x): + return x +</pre> <p>The function has a <a class="reference internal" href="../glossary#term-qualified-name"><span class="xref std std-term">qualified name</span></a> attribute to support introspection:</p> <pre data-language="pycon3">>>> D.f.__qualname__ +'D.f' +</pre> <p>Accessing the function through the class dictionary does not invoke <code>__get__()</code>. Instead, it just returns the underlying function object:</p> <pre data-language="python">>>> D.__dict__['f'] +<function D.f at 0x00C45070> +</pre> <p>Dotted access from a class calls <code>__get__()</code> which just returns the underlying function unchanged:</p> <pre data-language="python">>>> D.f +<function D.f at 0x00C45070> +</pre> <p>The interesting behavior occurs during dotted access from an instance. The dotted lookup calls <code>__get__()</code> which returns a bound method object:</p> <pre data-language="python">>>> d = D() +>>> d.f +<bound method D.f of <__main__.D object at 0x00B18C90>> +</pre> <p>Internally, the bound method stores the underlying function and the bound instance:</p> <pre data-language="python">>>> d.f.__func__ +<function D.f at 0x00C45070> + +>>> d.f.__self__ +<__main__.D object at 0x1012e1f98> +</pre> <p>If you have ever wondered where <em>self</em> comes from in regular methods or where <em>cls</em> comes from in class methods, this is it!</p> </section> <section id="kinds-of-methods"> <h3>Kinds of methods</h3> <p>Non-data descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.</p> <p>To recap, functions have a <code>__get__()</code> method so that they can be converted to a method when accessed as attributes. The non-data descriptor transforms an <code>obj.f(*args)</code> call into <code>f(obj, *args)</code>. Calling <code>cls.f(*args)</code> becomes <code>f(*args)</code>.</p> <p>This chart summarizes the binding and its two most useful variants:</p> <table class="docutils align-default"> <thead> <tr> +<th class="head"><p>Transformation</p></th> <th class="head"><p>Called from an object</p></th> <th class="head"><p>Called from a class</p></th> </tr> </thead> <tr> +<td><p>function</p></td> <td><p>f(obj, *args)</p></td> <td><p>f(*args)</p></td> </tr> <tr> +<td><p>staticmethod</p></td> <td><p>f(*args)</p></td> <td><p>f(*args)</p></td> </tr> <tr> +<td><p>classmethod</p></td> <td><p>f(type(obj), *args)</p></td> <td><p>f(cls, *args)</p></td> </tr> </table> </section> <section id="static-methods"> <h3>Static methods</h3> <p>Static methods return the underlying function without changes. Calling either <code>c.f</code> or <code>C.f</code> is the equivalent of a direct lookup into <code>object.__getattribute__(c, "f")</code> or <code>object.__getattribute__(C, "f")</code>. As a result, the function becomes identically accessible from either an object or a class.</p> <p>Good candidates for static methods are methods that do not reference the <code>self</code> variable.</p> <p>For instance, a statistics package may include a container class for experimental data. The class provides normal methods for computing the average, mean, median, and other descriptive statistics that depend on the data. However, there may be useful functions which are conceptually related but do not depend on the data. For instance, <code>erf(x)</code> is handy conversion routine that comes up in statistical work but does not directly depend on a particular dataset. It can be called either from an object or the class: <code>s.erf(1.5) --> .9332</code> or <code>Sample.erf(1.5) --> .9332</code>.</p> <p>Since static methods return the underlying function with no changes, the example calls are unexciting:</p> <pre data-language="python">class E: + @staticmethod + def f(x): + return x * 10 +</pre> <pre data-language="pycon3">>>> E.f(3) +30 +>>> E().f(3) +30 +</pre> <p>Using the non-data descriptor protocol, a pure Python version of <a class="reference internal" href="../library/functions#staticmethod" title="staticmethod"><code>staticmethod()</code></a> would look like this:</p> <pre data-language="python">import functools + +class StaticMethod: + "Emulate PyStaticMethod_Type() in Objects/funcobject.c" + + def __init__(self, f): + self.f = f + functools.update_wrapper(self, f) + + def __get__(self, obj, objtype=None): + return self.f + + def __call__(self, *args, **kwds): + return self.f(*args, **kwds) +</pre> <p>The <a class="reference internal" href="../library/functools#functools.update_wrapper" title="functools.update_wrapper"><code>functools.update_wrapper()</code></a> call adds a <code>__wrapped__</code> attribute that refers to the underlying function. Also it carries forward the attributes necessary to make the wrapper look like the wrapped function: <a class="reference internal" href="../reference/datamodel#function.__name__" title="function.__name__"><code>__name__</code></a>, <a class="reference internal" href="../reference/datamodel#function.__qualname__" title="function.__qualname__"><code>__qualname__</code></a>, <a class="reference internal" href="../reference/datamodel#function.__doc__" title="function.__doc__"><code>__doc__</code></a>, and <a class="reference internal" href="../reference/datamodel#function.__annotations__" title="function.__annotations__"><code>__annotations__</code></a>.</p> </section> <section id="class-methods"> <h3>Class methods</h3> <p>Unlike static methods, class methods prepend the class reference to the argument list before calling the function. This format is the same for whether the caller is an object or a class:</p> <pre data-language="python">class F: + @classmethod + def f(cls, x): + return cls.__name__, x +</pre> <pre data-language="pycon3">>>> F.f(3) +('F', 3) +>>> F().f(3) +('F', 3) +</pre> <p>This behavior is useful whenever the method only needs to have a class reference and does not rely on data stored in a specific instance. One use for class methods is to create alternate class constructors. For example, the classmethod <a class="reference internal" href="../library/stdtypes#dict.fromkeys" title="dict.fromkeys"><code>dict.fromkeys()</code></a> creates a new dictionary from a list of keys. The pure Python equivalent is:</p> <pre data-language="python">class Dict(dict): + @classmethod + def fromkeys(cls, iterable, value=None): + "Emulate dict_fromkeys() in Objects/dictobject.c" + d = cls() + for key in iterable: + d[key] = value + return d +</pre> <p>Now a new dictionary of unique keys can be constructed like this:</p> <pre data-language="pycon3">>>> d = Dict.fromkeys('abracadabra') +>>> type(d) is Dict +True +>>> d +{'a': None, 'b': None, 'r': None, 'c': None, 'd': None} +</pre> <p>Using the non-data descriptor protocol, a pure Python version of <a class="reference internal" href="../library/functions#classmethod" title="classmethod"><code>classmethod()</code></a> would look like this:</p> <pre data-language="python">import functools + +class ClassMethod: + "Emulate PyClassMethod_Type() in Objects/funcobject.c" + + def __init__(self, f): + self.f = f + functools.update_wrapper(self, f) + + def __get__(self, obj, cls=None): + if cls is None: + cls = type(obj) + if hasattr(type(self.f), '__get__'): + # This code path was added in Python 3.9 + # and was deprecated in Python 3.11. + return self.f.__get__(cls, cls) + return MethodType(self.f, cls) +</pre> <p>The code path for <code>hasattr(type(self.f), '__get__')</code> was added in Python 3.9 and makes it possible for <a class="reference internal" href="../library/functions#classmethod" title="classmethod"><code>classmethod()</code></a> to support chained decorators. For example, a classmethod and property could be chained together. In Python 3.11, this functionality was deprecated.</p> <pre data-language="python">class G: + @classmethod + @property + def __doc__(cls): + return f'A doc for {cls.__name__!r}' +</pre> <pre data-language="pycon3">>>> G.__doc__ +"A doc for 'G'" +</pre> <p>The <a class="reference internal" href="../library/functools#functools.update_wrapper" title="functools.update_wrapper"><code>functools.update_wrapper()</code></a> call in <code>ClassMethod</code> adds a <code>__wrapped__</code> attribute that refers to the underlying function. Also it carries forward the attributes necessary to make the wrapper look like the wrapped function: <a class="reference internal" href="../reference/datamodel#function.__name__" title="function.__name__"><code>__name__</code></a>, <a class="reference internal" href="../reference/datamodel#function.__qualname__" title="function.__qualname__"><code>__qualname__</code></a>, <a class="reference internal" href="../reference/datamodel#function.__doc__" title="function.__doc__"><code>__doc__</code></a>, and <a class="reference internal" href="../reference/datamodel#function.__annotations__" title="function.__annotations__"><code>__annotations__</code></a>.</p> </section> <section id="member-objects-and-slots"> <h3>Member objects and __slots__</h3> <p>When a class defines <code>__slots__</code>, it replaces instance dictionaries with a fixed-length array of slot values. From a user point of view that has several effects:</p> <p>1. Provides immediate detection of bugs due to misspelled attribute assignments. Only attribute names specified in <code>__slots__</code> are allowed:</p> <pre data-language="python">class Vehicle: + __slots__ = ('id_number', 'make', 'model') +</pre> <pre data-language="pycon3">>>> auto = Vehicle() +>>> auto.id_nubmer = 'VYE483814LQEX' +Traceback (most recent call last): + ... +AttributeError: 'Vehicle' object has no attribute 'id_nubmer' +</pre> <p>2. Helps create immutable objects where descriptors manage access to private attributes stored in <code>__slots__</code>:</p> <pre data-language="python">class Immutable: + + __slots__ = ('_dept', '_name') # Replace the instance dictionary + + def __init__(self, dept, name): + self._dept = dept # Store to private attribute + self._name = name # Store to private attribute + + @property # Read-only descriptor + def dept(self): + return self._dept + + @property + def name(self): # Read-only descriptor + return self._name +</pre> <pre data-language="pycon3">>>> mark = Immutable('Botany', 'Mark Watney') +>>> mark.dept +'Botany' +>>> mark.dept = 'Space Pirate' +Traceback (most recent call last): + ... +AttributeError: property 'dept' of 'Immutable' object has no setter +>>> mark.location = 'Mars' +Traceback (most recent call last): + ... +AttributeError: 'Immutable' object has no attribute 'location' +</pre> <p>3. Saves memory. On a 64-bit Linux build, an instance with two attributes takes 48 bytes with <code>__slots__</code> and 152 bytes without. This <a class="reference external" href="https://en.wikipedia.org/wiki/Flyweight_pattern">flyweight design pattern</a> likely only matters when a large number of instances are going to be created.</p> <p>4. Improves speed. Reading instance variables is 35% faster with <code>__slots__</code> (as measured with Python 3.10 on an Apple M1 processor).</p> <p>5. Blocks tools like <a class="reference internal" href="../library/functools#functools.cached_property" title="functools.cached_property"><code>functools.cached_property()</code></a> which require an instance dictionary to function correctly:</p> <pre data-language="python">from functools import cached_property + +class CP: + __slots__ = () # Eliminates the instance dict + + @cached_property # Requires an instance dict + def pi(self): + return 4 * sum((-1.0)**n / (2.0*n + 1.0) + for n in reversed(range(100_000))) +</pre> <pre data-language="pycon3">>>> CP().pi +Traceback (most recent call last): + ... +TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property. +</pre> <p>It is not possible to create an exact drop-in pure Python version of <code>__slots__</code> because it requires direct access to C structures and control over object memory allocation. However, we can build a mostly faithful simulation where the actual C structure for slots is emulated by a private <code>_slotvalues</code> list. Reads and writes to that private structure are managed by member descriptors:</p> <pre data-language="python">null = object() + +class Member: + + def __init__(self, name, clsname, offset): + 'Emulate PyMemberDef in Include/structmember.h' + # Also see descr_new() in Objects/descrobject.c + self.name = name + self.clsname = clsname + self.offset = offset + + def __get__(self, obj, objtype=None): + 'Emulate member_get() in Objects/descrobject.c' + # Also see PyMember_GetOne() in Python/structmember.c + if obj is None: + return self + value = obj._slotvalues[self.offset] + if value is null: + raise AttributeError(self.name) + return value + + def __set__(self, obj, value): + 'Emulate member_set() in Objects/descrobject.c' + obj._slotvalues[self.offset] = value + + def __delete__(self, obj): + 'Emulate member_delete() in Objects/descrobject.c' + value = obj._slotvalues[self.offset] + if value is null: + raise AttributeError(self.name) + obj._slotvalues[self.offset] = null + + def __repr__(self): + 'Emulate member_repr() in Objects/descrobject.c' + return f'<Member {self.name!r} of {self.clsname!r}>' +</pre> <p>The <code>type.__new__()</code> method takes care of adding member objects to class variables:</p> <pre data-language="python">class Type(type): + 'Simulate how the type metaclass adds member objects for slots' + + def __new__(mcls, clsname, bases, mapping, **kwargs): + 'Emulate type_new() in Objects/typeobject.c' + # type_new() calls PyTypeReady() which calls add_methods() + slot_names = mapping.get('slot_names', []) + for offset, name in enumerate(slot_names): + mapping[name] = Member(name, clsname, offset) + return type.__new__(mcls, clsname, bases, mapping, **kwargs) +</pre> <p>The <a class="reference internal" href="../reference/datamodel#object.__new__" title="object.__new__"><code>object.__new__()</code></a> method takes care of creating instances that have slots instead of an instance dictionary. Here is a rough simulation in pure Python:</p> <pre data-language="python">class Object: + 'Simulate how object.__new__() allocates memory for __slots__' + + def __new__(cls, *args, **kwargs): + 'Emulate object_new() in Objects/typeobject.c' + inst = super().__new__(cls) + if hasattr(cls, 'slot_names'): + empty_slots = [null] * len(cls.slot_names) + object.__setattr__(inst, '_slotvalues', empty_slots) + return inst + + def __setattr__(self, name, value): + 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' + cls = type(self) + if hasattr(cls, 'slot_names') and name not in cls.slot_names: + raise AttributeError( + f'{cls.__name__!r} object has no attribute {name!r}' + ) + super().__setattr__(name, value) + + def __delattr__(self, name): + 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' + cls = type(self) + if hasattr(cls, 'slot_names') and name not in cls.slot_names: + raise AttributeError( + f'{cls.__name__!r} object has no attribute {name!r}' + ) + super().__delattr__(name) +</pre> <p>To use the simulation in a real class, just inherit from <code>Object</code> and set the <a class="reference internal" href="../glossary#term-metaclass"><span class="xref std std-term">metaclass</span></a> to <code>Type</code>:</p> <pre data-language="python">class H(Object, metaclass=Type): + 'Instance variables stored in slots' + + slot_names = ['x', 'y'] + + def __init__(self, x, y): + self.x = x + self.y = y +</pre> <p>At this point, the metaclass has loaded member objects for <em>x</em> and <em>y</em>:</p> <pre data-language="python">>>> from pprint import pp +>>> pp(dict(vars(H))) +{'__module__': '__main__', + '__doc__': 'Instance variables stored in slots', + 'slot_names': ['x', 'y'], + '__init__': <function H.__init__ at 0x7fb5d302f9d0>, + 'x': <Member 'x' of 'H'>, + 'y': <Member 'y' of 'H'>} +</pre> <p>When instances are created, they have a <code>slot_values</code> list where the attributes are stored:</p> <pre data-language="pycon3">>>> h = H(10, 20) +>>> vars(h) +{'_slotvalues': [10, 20]} +>>> h.x = 55 +>>> vars(h) +{'_slotvalues': [55, 20]} +</pre> <p>Misspelled or unassigned attributes will raise an exception:</p> <pre data-language="pycon3">>>> h.xz +Traceback (most recent call last): + ... +AttributeError: 'H' object has no attribute 'xz' +</pre> </section> </section> <div class="_attribution"> + <p class="_attribution-p"> + © 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br> + <a href="https://docs.python.org/3.12/howto/descriptor.html" class="_attribution-link">https://docs.python.org/3.12/howto/descriptor.html</a> + </p> +</div> |
