CINXE.COM

PEP 3133 – Introducing Roles | peps.python.org

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="color-scheme" content="light dark"> <title>PEP 3133 – Introducing Roles | peps.python.org</title> <link rel="shortcut icon" href="../_static/py.png"> <link rel="canonical" href="https://peps.python.org/pep-3133/"> <link rel="stylesheet" href="../_static/style.css" type="text/css"> <link rel="stylesheet" href="../_static/mq.css" type="text/css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" media="(prefers-color-scheme: light)" id="pyg-light"> <link rel="stylesheet" href="../_static/pygments_dark.css" type="text/css" media="(prefers-color-scheme: dark)" id="pyg-dark"> <link rel="alternate" type="application/rss+xml" title="Latest PEPs" href="https://peps.python.org/peps.rss"> <meta property="og:title" content='PEP 3133 – Introducing Roles | peps.python.org'> <meta property="og:description" content="Python’s existing object model organizes objects according to their implementation. It is often desirable – especially in duck typing-based language like Python – to organize objects by the part they play in a larger system (their intent), rather than ..."> <meta property="og:type" content="website"> <meta property="og:url" content="https://peps.python.org/pep-3133/"> <meta property="og:site_name" content="Python Enhancement Proposals (PEPs)"> <meta property="og:image" content="https://peps.python.org/_static/og-image.png"> <meta property="og:image:alt" content="Python PEPs"> <meta property="og:image:width" content="200"> <meta property="og:image:height" content="200"> <meta name="description" content="Python’s existing object model organizes objects according to their implementation. It is often desirable – especially in duck typing-based language like Python – to organize objects by the part they play in a larger system (their intent), rather than ..."> <meta name="theme-color" content="#3776ab"> </head> <body> <svg xmlns="http://www.w3.org/2000/svg" style="display: none;"> <symbol id="svg-sun-half" viewBox="0 0 24 24" pointer-events="all"> <title>Following system colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="12" cy="12" r="9"></circle> <path d="M12 3v18m0-12l4.65-4.65M12 14.3l7.37-7.37M12 19.6l8.85-8.85"></path> </svg> </symbol> <symbol id="svg-moon" viewBox="0 0 24 24" pointer-events="all"> <title>Selected dark colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454z"></path> </svg> </symbol> <symbol id="svg-sun" viewBox="0 0 24 24" pointer-events="all"> <title>Selected light colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="12" cy="12" r="5"></circle> <line x1="12" y1="1" x2="12" y2="3"></line> <line x1="12" y1="21" x2="12" y2="23"></line> <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line> <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line> <line x1="1" y1="12" x2="3" y2="12"></line> <line x1="21" y1="12" x2="23" y2="12"></line> <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line> <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line> </svg> </symbol> </svg> <script> document.documentElement.dataset.colour_scheme = localStorage.getItem("colour_scheme") || "auto" </script> <section id="pep-page-section"> <header> <h1>Python Enhancement Proposals</h1> <ul class="breadcrumbs"> <li><a href="https://www.python.org/" title="The Python Programming Language">Python</a> &raquo; </li> <li><a href="../pep-0000/">PEP Index</a> &raquo; </li> <li>PEP 3133</li> </ul> <button id="colour-scheme-cycler" onClick="setColourScheme(nextColourScheme())"> <svg aria-hidden="true" class="colour-scheme-icon-when-auto"><use href="#svg-sun-half"></use></svg> <svg aria-hidden="true" class="colour-scheme-icon-when-dark"><use href="#svg-moon"></use></svg> <svg aria-hidden="true" class="colour-scheme-icon-when-light"><use href="#svg-sun"></use></svg> <span class="visually-hidden">Toggle light / dark / auto colour theme</span> </button> </header> <article> <section id="pep-content"> <h1 class="page-title">PEP 3133 – Introducing Roles</h1> <dl class="rfc2822 field-list simple"> <dt class="field-odd">Author<span class="colon">:</span></dt> <dd class="field-odd">Collin Winter &lt;collinwinter&#32;&#97;t&#32;google.com&gt;</dd> <dt class="field-even">Status<span class="colon">:</span></dt> <dd class="field-even"><abbr title="Formally declined and will not be accepted">Rejected</abbr></dd> <dt class="field-odd">Type<span class="colon">:</span></dt> <dd class="field-odd"><abbr title="Normative PEP with a new feature for Python, implementation change for CPython or interoperability standard for the ecosystem">Standards Track</abbr></dd> <dt class="field-even">Requires<span class="colon">:</span></dt> <dd class="field-even"><a class="reference external" href="../pep-3115/">3115</a>, <a class="reference external" href="../pep-3129/">3129</a></dd> <dt class="field-odd">Created<span class="colon">:</span></dt> <dd class="field-odd">01-May-2007</dd> <dt class="field-even">Python-Version<span class="colon">:</span></dt> <dd class="field-even">3.0</dd> <dt class="field-odd">Post-History<span class="colon">:</span></dt> <dd class="field-odd">13-May-2007</dd> </dl> <hr class="docutils" /> <section id="contents"> <details><summary>Table of Contents</summary><ul class="simple"> <li><a class="reference internal" href="#rejection-notice">Rejection Notice</a></li> <li><a class="reference internal" href="#abstract">Abstract</a></li> <li><a class="reference internal" href="#rationale">Rationale</a><ul> <li><a class="reference internal" href="#a-note-on-syntax">A Note on Syntax</a></li> </ul> </li> <li><a class="reference internal" href="#performing-your-role">Performing Your Role</a><ul> <li><a class="reference internal" href="#static-role-assignment">Static Role Assignment</a></li> <li><a class="reference internal" href="#assigning-roles-at-runtime">Assigning Roles at Runtime</a></li> <li><a class="reference internal" href="#asking-questions-about-roles">Asking Questions About Roles</a></li> </ul> </li> <li><a class="reference internal" href="#defining-new-roles">Defining New Roles</a><ul> <li><a class="reference internal" href="#empty-roles">Empty Roles</a></li> <li><a class="reference internal" href="#composing-roles-via-inheritance">Composing Roles via Inheritance</a></li> <li><a class="reference internal" href="#requiring-concrete-methods">Requiring Concrete Methods</a></li> </ul> </li> <li><a class="reference internal" href="#mechanism">Mechanism</a></li> <li><a class="reference internal" href="#relationship-to-abstract-base-classes">Relationship to Abstract Base Classes</a></li> <li><a class="reference internal" href="#open-issues">Open Issues</a><ul> <li><a class="reference internal" href="#allowing-instances-to-perform-different-roles-than-their-class">Allowing Instances to Perform Different Roles Than Their Class</a></li> <li><a class="reference internal" href="#requiring-attributes">Requiring Attributes</a></li> <li><a class="reference internal" href="#roles-of-roles">Roles of Roles</a></li> <li><a class="reference internal" href="#class-performs">class_performs()</a></li> <li><a class="reference internal" href="#prettier-dynamic-role-assignment">Prettier Dynamic Role Assignment</a></li> <li><a class="reference internal" href="#syntax-support">Syntax Support</a></li> </ul> </li> <li><a class="reference internal" href="#implementation">Implementation</a></li> <li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li> <li><a class="reference internal" href="#references">References</a></li> <li><a class="reference internal" href="#copyright">Copyright</a></li> </ul> </details></section> <section id="rejection-notice"> <h2><a class="toc-backref" href="#rejection-notice" role="doc-backlink">Rejection Notice</a></h2> <p>This PEP has helped push <a class="pep reference internal" href="../pep-3119/" title="PEP 3119 – Introducing Abstract Base Classes">PEP 3119</a> towards a saner, more minimalistic approach. But given the latest version of <a class="pep reference internal" href="../pep-3119/" title="PEP 3119 – Introducing Abstract Base Classes">PEP 3119</a> I much prefer that. GvR.</p> </section> <section id="abstract"> <h2><a class="toc-backref" href="#abstract" role="doc-backlink">Abstract</a></h2> <p>Python’s existing object model organizes objects according to their implementation. It is often desirable – especially in duck typing-based language like Python – to organize objects by the part they play in a larger system (their intent), rather than by how they fulfill that part (their implementation). This PEP introduces the concept of roles, a mechanism for organizing objects according to their intent rather than their implementation.</p> </section> <section id="rationale"> <h2><a class="toc-backref" href="#rationale" role="doc-backlink">Rationale</a></h2> <p>In the beginning were objects. They allowed programmers to marry function and state, and to increase code reusability through concepts like polymorphism and inheritance, and lo, it was good. There came a time, however, when inheritance and polymorphism weren’t enough. With the invention of both dogs and trees, we were no longer able to be content with knowing merely, “Does it understand ‘bark’?” We now needed to know what a given object thought that “bark” meant.</p> <p>One solution, the one detailed here, is that of roles, a mechanism orthogonal and complementary to the traditional class/instance system. Whereas classes concern themselves with state and implementation, the roles mechanism deals exclusively with the behaviours embodied in a given class.</p> <p>This system was originally called “traits” and implemented for Squeak Smalltalk <a class="footnote-reference brackets" href="#traits-paper" id="id1">[4]</a>. It has since been adapted for use in Perl 6 <a class="footnote-reference brackets" href="#perl6-s12" id="id2">[3]</a> where it is called “roles”, and it is primarily from there that the concept is now being interpreted for Python 3. Python 3 will preserve the name “roles”.</p> <p>In a nutshell: roles tell you <em>what</em> an object does, classes tell you <em>how</em> an object does it.</p> <p>In this PEP, I will outline a system for Python 3 that will make it possible to easily determine whether a given object’s understanding of “bark” is tree-like or dog-like. (There might also be more serious examples.)</p> <section id="a-note-on-syntax"> <h3><a class="toc-backref" href="#a-note-on-syntax" role="doc-backlink">A Note on Syntax</a></h3> <p>A syntax proposals in this PEP are tentative and should be considered to be strawmen. The necessary bits that this PEP depends on – namely <a class="pep reference internal" href="../pep-3115/" title="PEP 3115 – Metaclasses in Python 3000">PEP 3115</a>’s class definition syntax and <a class="pep reference internal" href="../pep-3129/" title="PEP 3129 – Class Decorators">PEP 3129</a>’s class decorators – are still being formalized and may change. Function names will, of course, be subject to lengthy bikeshedding debates.</p> </section> </section> <section id="performing-your-role"> <h2><a class="toc-backref" href="#performing-your-role" role="doc-backlink">Performing Your Role</a></h2> <section id="static-role-assignment"> <h3><a class="toc-backref" href="#static-role-assignment" role="doc-backlink">Static Role Assignment</a></h3> <p>Let’s start out by defining <code class="docutils literal notranslate"><span class="pre">Tree</span></code> and <code class="docutils literal notranslate"><span class="pre">Dog</span></code> classes</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Tree</span><span class="p">(</span><span class="n">Vegetable</span><span class="p">):</span> <span class="k">def</span> <span class="nf">bark</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">is_rough</span><span class="p">()</span> <span class="k">class</span> <span class="nc">Dog</span><span class="p">(</span><span class="n">Animal</span><span class="p">):</span> <span class="k">def</span> <span class="nf">bark</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">goes_ruff</span><span class="p">()</span> </pre></div> </div> <p>While both implement a <code class="docutils literal notranslate"><span class="pre">bark()</span></code> method with the same signature, they do wildly different things. We need some way of differentiating what we’re expecting. Relying on inheritance and a simple <code class="docutils literal notranslate"><span class="pre">isinstance()</span></code> test will limit code reuse and/or force any dog-like classes to inherit from <code class="docutils literal notranslate"><span class="pre">Dog</span></code>, whether or not that makes sense. Let’s see if roles can help.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@perform_role</span><span class="p">(</span><span class="n">Doglike</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Dog</span><span class="p">(</span><span class="n">Animal</span><span class="p">):</span> <span class="o">...</span> <span class="nd">@perform_role</span><span class="p">(</span><span class="n">Treelike</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Tree</span><span class="p">(</span><span class="n">Vegetable</span><span class="p">):</span> <span class="o">...</span> <span class="nd">@perform_role</span><span class="p">(</span><span class="n">SitThere</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Rock</span><span class="p">(</span><span class="n">Mineral</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>We use class decorators from <a class="pep reference internal" href="../pep-3129/" title="PEP 3129 – Class Decorators">PEP 3129</a> to associate a particular role or roles with a class. Client code can now verify that an incoming object performs the <code class="docutils literal notranslate"><span class="pre">Doglike</span></code> role, allowing it to handle <code class="docutils literal notranslate"><span class="pre">Wolf</span></code>, <code class="docutils literal notranslate"><span class="pre">LaughingHyena</span></code> and <code class="docutils literal notranslate"><span class="pre">Aibo</span></code> <a class="footnote-reference brackets" href="#aibo" id="id3">[1]</a> instances, too.</p> <p>Roles can be composed via normal inheritance:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@perform_role</span><span class="p">(</span><span class="n">Guard</span><span class="p">,</span> <span class="n">MummysLittleDarling</span><span class="p">)</span> <span class="k">class</span> <span class="nc">GermanShepherd</span><span class="p">(</span><span class="n">Dog</span><span class="p">):</span> <span class="k">def</span> <span class="nf">guard</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">the_precious</span><span class="p">):</span> <span class="k">while</span> <span class="kc">True</span><span class="p">:</span> <span class="k">if</span> <span class="n">intruder_near</span><span class="p">(</span><span class="n">the_precious</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">growl</span><span class="p">()</span> <span class="k">def</span> <span class="nf">get_petted</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">swallow_pride</span><span class="p">()</span> </pre></div> </div> <p>Here, <code class="docutils literal notranslate"><span class="pre">GermanShepherd</span></code> instances perform three roles: <code class="docutils literal notranslate"><span class="pre">Guard</span></code> and <code class="docutils literal notranslate"><span class="pre">MummysLittleDarling</span></code> are applied directly, whereas <code class="docutils literal notranslate"><span class="pre">Doglike</span></code> is inherited from <code class="docutils literal notranslate"><span class="pre">Dog</span></code>.</p> </section> <section id="assigning-roles-at-runtime"> <h3><a class="toc-backref" href="#assigning-roles-at-runtime" role="doc-backlink">Assigning Roles at Runtime</a></h3> <p>Roles can be assigned at runtime, too, by unpacking the syntactic sugar provided by decorators.</p> <p>Say we import a <code class="docutils literal notranslate"><span class="pre">Robot</span></code> class from another module, and since we know that <code class="docutils literal notranslate"><span class="pre">Robot</span></code> already implements our <code class="docutils literal notranslate"><span class="pre">Guard</span></code> interface, we’d like it to play nicely with guard-related code, too.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">perform</span><span class="p">(</span><span class="n">Guard</span><span class="p">)(</span><span class="n">Robot</span><span class="p">)</span> </pre></div> </div> <p>This takes effect immediately and impacts all instances of <code class="docutils literal notranslate"><span class="pre">Robot</span></code>.</p> </section> <section id="asking-questions-about-roles"> <h3><a class="toc-backref" href="#asking-questions-about-roles" role="doc-backlink">Asking Questions About Roles</a></h3> <p>Just because we’ve told our robot army that they’re guards, we’d like to check in on them occasionally and make sure they’re still at their task.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">performs</span><span class="p">(</span><span class="n">our_robot</span><span class="p">,</span> <span class="n">Guard</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> <p>What about that one robot over there?</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">performs</span><span class="p">(</span><span class="n">that_robot_over_there</span><span class="p">,</span> <span class="n">Guard</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> <p>The <code class="docutils literal notranslate"><span class="pre">performs()</span></code> function is used to ask if a given object fulfills a given role. It cannot be used, however, to ask a class if its instances fulfill a role:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">performs</span><span class="p">(</span><span class="n">Robot</span><span class="p">,</span> <span class="n">Guard</span><span class="p">)</span> <span class="go">False</span> </pre></div> </div> <p>This is because the <code class="docutils literal notranslate"><span class="pre">Robot</span></code> class is not interchangeable with a <code class="docutils literal notranslate"><span class="pre">Robot</span></code> instance.</p> </section> </section> <section id="defining-new-roles"> <h2><a class="toc-backref" href="#defining-new-roles" role="doc-backlink">Defining New Roles</a></h2> <section id="empty-roles"> <h3><a class="toc-backref" href="#empty-roles" role="doc-backlink">Empty Roles</a></h3> <p>Roles are defined like a normal class, but use the <code class="docutils literal notranslate"><span class="pre">Role</span></code> metaclass.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Doglike</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Role</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>Metaclasses are used to indicate that <code class="docutils literal notranslate"><span class="pre">Doglike</span></code> is a <code class="docutils literal notranslate"><span class="pre">Role</span></code> in the same way 5 is an <code class="docutils literal notranslate"><span class="pre">int</span></code> and <code class="docutils literal notranslate"><span class="pre">tuple</span></code> is a <code class="docutils literal notranslate"><span class="pre">type</span></code>.</p> </section> <section id="composing-roles-via-inheritance"> <h3><a class="toc-backref" href="#composing-roles-via-inheritance" role="doc-backlink">Composing Roles via Inheritance</a></h3> <p>Roles may inherit from other roles; this has the effect of composing them. Here, instances of <code class="docutils literal notranslate"><span class="pre">Dog</span></code> will perform both the <code class="docutils literal notranslate"><span class="pre">Doglike</span></code> and <code class="docutils literal notranslate"><span class="pre">FourLegs</span></code> roles.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">FourLegs</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Role</span><span class="p">):</span> <span class="k">pass</span> <span class="k">class</span> <span class="nc">Doglike</span><span class="p">(</span><span class="n">FourLegs</span><span class="p">,</span> <span class="n">Carnivor</span><span class="p">):</span> <span class="k">pass</span> <span class="nd">@perform_role</span><span class="p">(</span><span class="n">Doglike</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Dog</span><span class="p">(</span><span class="n">Mammal</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> </section> <section id="requiring-concrete-methods"> <h3><a class="toc-backref" href="#requiring-concrete-methods" role="doc-backlink">Requiring Concrete Methods</a></h3> <p>So far we’ve only defined empty roles – not very useful things. Let’s now require that all classes that claim to fulfill the <code class="docutils literal notranslate"><span class="pre">Doglike</span></code> role define a <code class="docutils literal notranslate"><span class="pre">bark()</span></code> method:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Doglike</span><span class="p">(</span><span class="n">FourLegs</span><span class="p">):</span> <span class="k">def</span> <span class="nf">bark</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> <p>No decorators are required to flag the method as “abstract”, and the method will never be called, meaning whatever code it contains (if any) is irrelevant. Roles provide <em>only</em> abstract methods; concrete default implementations are left to other, better-suited mechanisms like mixins.</p> <p>Once you have defined a role, and a class has claimed to perform that role, it is essential that that claim be verified. Here, the programmer has misspelled one of the methods required by the role.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@perform_role</span><span class="p">(</span><span class="n">FourLegs</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Horse</span><span class="p">(</span><span class="n">Mammal</span><span class="p">):</span> <span class="k">def</span> <span class="nf">run_like_teh_wind</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">...</span> </pre></div> </div> <p>This will cause the role system to raise an exception, complaining that you’re missing a <code class="docutils literal notranslate"><span class="pre">run_like_the_wind()</span></code> method. The role system carries out these checks as soon as a class is flagged as performing a given role.</p> <p>Concrete methods are required to match exactly the signature demanded by the role. Here, we’ve attempted to fulfill our role by defining a concrete version of <code class="docutils literal notranslate"><span class="pre">bark()</span></code>, but we’ve missed the mark a bit.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@perform_role</span><span class="p">(</span><span class="n">Doglike</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Coyote</span><span class="p">(</span><span class="n">Mammal</span><span class="p">):</span> <span class="k">def</span> <span class="nf">bark</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">target</span><span class="o">=</span><span class="n">moon</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> <p>This method’s signature doesn’t match exactly with what the <code class="docutils literal notranslate"><span class="pre">Doglike</span></code> role was expecting, so the role system will throw a bit of a tantrum.</p> </section> </section> <section id="mechanism"> <h2><a class="toc-backref" href="#mechanism" role="doc-backlink">Mechanism</a></h2> <p>The following are strawman proposals for how roles might be expressed in Python. The examples here are phrased in a way that the roles mechanism may be implemented without changing the Python interpreter. (Examples adapted from an article on Perl 6 roles by Curtis Poe <a class="footnote-reference brackets" href="#roles-examples" id="id4">[2]</a>.)</p> <ol class="arabic"> <li>Static class role assignment<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@perform_role</span><span class="p">(</span><span class="n">Thieving</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Elf</span><span class="p">(</span><span class="n">Character</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p><code class="docutils literal notranslate"><span class="pre">perform_role()</span></code> accepts multiple arguments, such that this is also legal:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@perform_role</span><span class="p">(</span><span class="n">Thieving</span><span class="p">,</span> <span class="n">Spying</span><span class="p">,</span> <span class="n">Archer</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Elf</span><span class="p">(</span><span class="n">Character</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>The <code class="docutils literal notranslate"><span class="pre">Elf</span></code> class now performs both the <code class="docutils literal notranslate"><span class="pre">Thieving</span></code>, <code class="docutils literal notranslate"><span class="pre">Spying</span></code>, and <code class="docutils literal notranslate"><span class="pre">Archer</span></code> roles.</p> </li> <li>Querying instances<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">performs</span><span class="p">(</span><span class="n">my_elf</span><span class="p">,</span> <span class="n">Thieving</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>The second argument to <code class="docutils literal notranslate"><span class="pre">performs()</span></code> may also be anything with a <code class="docutils literal notranslate"><span class="pre">__contains__()</span></code> method, meaning the following is legal:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">performs</span><span class="p">(</span><span class="n">my_elf</span><span class="p">,</span> <span class="nb">set</span><span class="p">([</span><span class="n">Thieving</span><span class="p">,</span> <span class="n">Spying</span><span class="p">,</span> <span class="n">BoyScout</span><span class="p">])):</span> <span class="o">...</span> </pre></div> </div> <p>Like <code class="docutils literal notranslate"><span class="pre">isinstance()</span></code>, the object needs only to perform a single role out of the set in order for the expression to be true.</p> </li> </ol> </section> <section id="relationship-to-abstract-base-classes"> <h2><a class="toc-backref" href="#relationship-to-abstract-base-classes" role="doc-backlink">Relationship to Abstract Base Classes</a></h2> <p>Early drafts of this PEP <a class="footnote-reference brackets" href="#proposal" id="id5">[5]</a> envisioned roles as competing with the abstract base classes proposed in <a class="pep reference internal" href="../pep-3119/" title="PEP 3119 – Introducing Abstract Base Classes">PEP 3119</a>. After further discussion and deliberation, a compromise and a delegation of responsibilities and use-cases has been worked out as follows:</p> <ul> <li>Roles provide a way of indicating an object’s semantics and abstract capabilities. A role may define abstract methods, but only as a way of delineating an interface through which a particular set of semantics are accessed. An <code class="docutils literal notranslate"><span class="pre">Ordering</span></code> role might require that some set of ordering operators be defined.<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Ordering</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Role</span><span class="p">):</span> <span class="k">def</span> <span class="fm">__ge__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">pass</span> <span class="k">def</span> <span class="fm">__le__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">pass</span> <span class="k">def</span> <span class="fm">__ne__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">pass</span> <span class="c1"># ...and so on</span> </pre></div> </div> <p>In this way, we’re able to indicate an object’s role or function within a larger system without constraining or concerning ourselves with a particular implementation.</p> </li> <li>Abstract base classes, by contrast, are a way of reusing common, discrete units of implementation. For example, one might define an <code class="docutils literal notranslate"><span class="pre">OrderingMixin</span></code> that implements several ordering operators in terms of other operators.<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">OrderingMixin</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__ge__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span> <span class="o">&gt;</span> <span class="n">other</span> <span class="ow">or</span> <span class="bp">self</span> <span class="o">==</span> <span class="n">other</span> <span class="k">def</span> <span class="fm">__le__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span> <span class="o">&lt;</span> <span class="n">other</span> <span class="ow">or</span> <span class="bp">self</span> <span class="o">==</span> <span class="n">other</span> <span class="k">def</span> <span class="fm">__ne__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">return</span> <span class="ow">not</span> <span class="bp">self</span> <span class="o">==</span> <span class="n">other</span> <span class="c1"># ...and so on</span> </pre></div> </div> <p>Using this abstract base class - more properly, a concrete mixin - allows a programmer to define a limited set of operators and let the mixin in effect “derive” the others.</p> </li> </ul> <p>By combining these two orthogonal systems, we’re able to both a) provide functionality, and b) alert consumer systems to the presence and availability of this functionality. For example, since the <code class="docutils literal notranslate"><span class="pre">OrderingMixin</span></code> class above satisfies the interface and semantics expressed in the <code class="docutils literal notranslate"><span class="pre">Ordering</span></code> role, we say the mixin performs the role:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@perform_role</span><span class="p">(</span><span class="n">Ordering</span><span class="p">)</span> <span class="k">class</span> <span class="nc">OrderingMixin</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__ge__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span> <span class="o">&gt;</span> <span class="n">other</span> <span class="ow">or</span> <span class="bp">self</span> <span class="o">==</span> <span class="n">other</span> <span class="k">def</span> <span class="fm">__le__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span> <span class="o">&lt;</span> <span class="n">other</span> <span class="ow">or</span> <span class="bp">self</span> <span class="o">==</span> <span class="n">other</span> <span class="k">def</span> <span class="fm">__ne__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="k">return</span> <span class="ow">not</span> <span class="bp">self</span> <span class="o">==</span> <span class="n">other</span> <span class="c1"># ...and so on</span> </pre></div> </div> <p>Now, any class that uses the mixin will automatically – that is, without further programmer effort – be tagged as performing the <code class="docutils literal notranslate"><span class="pre">Ordering</span></code> role.</p> <p>The separation of concerns into two distinct, orthogonal systems is desirable because it allows us to use each one separately. Take, for example, a third-party package providing a <code class="docutils literal notranslate"><span class="pre">RecursiveHash</span></code> role that indicates a container takes its contents into account when determining its hash value. Since Python’s built-in <code class="docutils literal notranslate"><span class="pre">tuple</span></code> and <code class="docutils literal notranslate"><span class="pre">frozenset</span></code> classes follow this semantic, the <code class="docutils literal notranslate"><span class="pre">RecursiveHash</span></code> role can be applied to them.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">perform_role</span><span class="p">(</span><span class="n">RecursiveHash</span><span class="p">)(</span><span class="nb">tuple</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">perform_role</span><span class="p">(</span><span class="n">RecursiveHash</span><span class="p">)(</span><span class="nb">frozenset</span><span class="p">)</span> </pre></div> </div> <p>Now, any code that consumes <code class="docutils literal notranslate"><span class="pre">RecursiveHash</span></code> objects will now be able to consume tuples and frozensets.</p> </section> <section id="open-issues"> <h2><a class="toc-backref" href="#open-issues" role="doc-backlink">Open Issues</a></h2> <section id="allowing-instances-to-perform-different-roles-than-their-class"> <h3><a class="toc-backref" href="#allowing-instances-to-perform-different-roles-than-their-class" role="doc-backlink">Allowing Instances to Perform Different Roles Than Their Class</a></h3> <p>Perl 6 allows instances to perform different roles than their class. These changes are local to the single instance and do not affect other instances of the class. For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">my_elf</span> <span class="o">=</span> <span class="n">Elf</span><span class="p">()</span> <span class="n">my_elf</span><span class="o">.</span><span class="n">goes_on_quest</span><span class="p">()</span> <span class="n">my_elf</span><span class="o">.</span><span class="n">becomes_evil</span><span class="p">()</span> <span class="n">now_performs</span><span class="p">(</span><span class="n">my_elf</span><span class="p">,</span> <span class="n">Thieving</span><span class="p">)</span> <span class="c1"># Only this one elf is a thief</span> <span class="n">my_elf</span><span class="o">.</span><span class="n">steals</span><span class="p">([</span><span class="s2">&quot;purses&quot;</span><span class="p">,</span> <span class="s2">&quot;candy&quot;</span><span class="p">,</span> <span class="s2">&quot;kisses&quot;</span><span class="p">])</span> </pre></div> </div> <p>In Perl 6, this is done by creating an anonymous class that inherits from the instance’s original parent and performs the additional role(s). This is possible in Python 3, though whether it is desirable is still is another matter.</p> <p>Inclusion of this feature would, of course, make it much easier to express the works of Charles Dickens in Python:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">literature</span> <span class="kn">import</span> <span class="n">role</span><span class="p">,</span> <span class="n">BildungsRoman</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">dickens</span> <span class="kn">import</span> <span class="n">Urchin</span><span class="p">,</span> <span class="n">Gentleman</span> <span class="gp">&gt;&gt;&gt;</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">BildungsRoman</span><span class="p">()</span> <span class="k">as</span> <span class="n">OliverTwist</span><span class="p">:</span> <span class="gp">... </span> <span class="n">mr_brownlow</span> <span class="o">=</span> <span class="n">Gentleman</span><span class="p">()</span> <span class="gp">... </span> <span class="n">oliver</span><span class="p">,</span> <span class="n">artful_dodger</span> <span class="o">=</span> <span class="n">Urchin</span><span class="p">(),</span> <span class="n">Urchin</span><span class="p">()</span> <span class="gp">... </span> <span class="n">now_performs</span><span class="p">(</span><span class="n">artful_dodger</span><span class="p">,</span> <span class="p">[</span><span class="n">role</span><span class="o">.</span><span class="n">Thief</span><span class="p">,</span> <span class="n">role</span><span class="o">.</span><span class="n">Scoundrel</span><span class="p">])</span> <span class="gp">...</span> <span class="gp">... </span> <span class="n">oliver</span><span class="o">.</span><span class="n">has_adventures_with</span><span class="p">(</span><span class="n">ArtfulDodger</span><span class="p">)</span> <span class="gp">... </span> <span class="n">mr_brownlow</span><span class="o">.</span><span class="n">adopt_orphan</span><span class="p">(</span><span class="n">oliver</span><span class="p">)</span> <span class="gp">... </span> <span class="n">now_performs</span><span class="p">(</span><span class="n">oliver</span><span class="p">,</span> <span class="n">role</span><span class="o">.</span><span class="n">RichWard</span><span class="p">)</span> </pre></div> </div> </section> <section id="requiring-attributes"> <h3><a class="toc-backref" href="#requiring-attributes" role="doc-backlink">Requiring Attributes</a></h3> <p>Neal Norwitz has requested the ability to make assertions about the presence of attributes using the same mechanism used to require methods. Since roles take effect at class definition-time, and since the vast majority of attributes are defined at runtime by a class’s <code class="docutils literal notranslate"><span class="pre">__init__()</span></code> method, there doesn’t seem to be a good way to check for attributes at the same time as methods.</p> <p>It may still be desirable to include non-enforced attributes in the role definition, if only for documentation purposes.</p> </section> <section id="roles-of-roles"> <h3><a class="toc-backref" href="#roles-of-roles" role="doc-backlink">Roles of Roles</a></h3> <p>Under the proposed semantics, it is possible for roles to have roles of their own.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@perform_role</span><span class="p">(</span><span class="n">Y</span><span class="p">)</span> <span class="k">class</span> <span class="nc">X</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Role</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>While this is possible, it is meaningless, since roles are generally not instantiated. There has been some off-line discussion about giving meaning to this expression, but so far no good ideas have emerged.</p> </section> <section id="class-performs"> <h3><a class="toc-backref" href="#class-performs" role="doc-backlink">class_performs()</a></h3> <p>It is currently not possible to ask a class if its instances perform a given role. It may be desirable to provide an analogue to <code class="docutils literal notranslate"><span class="pre">performs()</span></code> such that</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">my_dwarf</span><span class="p">,</span> <span class="n">Dwarf</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">performs</span><span class="p">(</span><span class="n">my_dwarf</span><span class="p">,</span> <span class="n">Surly</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">performs</span><span class="p">(</span><span class="n">Dwarf</span><span class="p">,</span> <span class="n">Surly</span><span class="p">)</span> <span class="go">False</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">class_performs</span><span class="p">(</span><span class="n">Dwarf</span><span class="p">,</span> <span class="n">Surly</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> </section> <section id="prettier-dynamic-role-assignment"> <h3><a class="toc-backref" href="#prettier-dynamic-role-assignment" role="doc-backlink">Prettier Dynamic Role Assignment</a></h3> <p>An early draft of this PEP included a separate mechanism for dynamically assigning a role to a class. This was spelled</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">now_perform</span><span class="p">(</span><span class="n">Dwarf</span><span class="p">,</span> <span class="n">GoldMiner</span><span class="p">)</span> </pre></div> </div> <p>This same functionality already exists by unpacking the syntactic sugar provided by decorators:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">perform_role</span><span class="p">(</span><span class="n">GoldMiner</span><span class="p">)(</span><span class="n">Dwarf</span><span class="p">)</span> </pre></div> </div> <p>At issue is whether dynamic role assignment is sufficiently important to warrant a dedicated spelling.</p> </section> <section id="syntax-support"> <h3><a class="toc-backref" href="#syntax-support" role="doc-backlink">Syntax Support</a></h3> <p>Though the phrasings laid out in this PEP are designed so that the roles system could be shipped as a stand-alone package, it may be desirable to add special syntax for defining, assigning and querying roles. One example might be a role keyword, which would translate</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyRole</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Role</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>into</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">role</span> <span class="n">MyRole</span><span class="p">:</span> <span class="o">...</span> </pre></div> </div> <p>Assigning a role could take advantage of the class definition arguments proposed in <a class="pep reference internal" href="../pep-3115/" title="PEP 3115 – Metaclasses in Python 3000">PEP 3115</a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="n">performs</span><span class="o">=</span><span class="n">MyRole</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> </section> </section> <section id="implementation"> <h2><a class="toc-backref" href="#implementation" role="doc-backlink">Implementation</a></h2> <p>A reference implementation is forthcoming.</p> </section> <section id="acknowledgements"> <h2><a class="toc-backref" href="#acknowledgements" role="doc-backlink">Acknowledgements</a></h2> <p>Thanks to Jeffery Yasskin, Talin and Guido van Rossum for several hours of in-person discussion to iron out the differences, overlap and finer points of roles and abstract base classes.</p> </section> <section id="references"> <h2><a class="toc-backref" href="#references" role="doc-backlink">References</a></h2> <aside class="footnote-list brackets"> <aside class="footnote brackets" id="aibo" role="doc-footnote"> <dt class="label" id="aibo">[<a href="#id3">1</a>]</dt> <dd><a class="reference external" href="http://en.wikipedia.org/wiki/AIBO">http://en.wikipedia.org/wiki/AIBO</a></aside> <aside class="footnote brackets" id="roles-examples" role="doc-footnote"> <dt class="label" id="roles-examples">[<a href="#id4">2</a>]</dt> <dd><a class="reference external" href="http://www.perlmonks.org/?node_id=384858">http://www.perlmonks.org/?node_id=384858</a></aside> <aside class="footnote brackets" id="perl6-s12" role="doc-footnote"> <dt class="label" id="perl6-s12">[<a href="#id2">3</a>]</dt> <dd><a class="reference external" href="http://dev.perl.org/perl6/doc/design/syn/S12.html">http://dev.perl.org/perl6/doc/design/syn/S12.html</a></aside> <aside class="footnote brackets" id="traits-paper" role="doc-footnote"> <dt class="label" id="traits-paper">[<a href="#id1">4</a>]</dt> <dd><a class="reference external" href="http://www.iam.unibe.ch/~scg/Archive/Papers/Scha03aTraits.pdf">http://www.iam.unibe.ch/~scg/Archive/Papers/Scha03aTraits.pdf</a></aside> <aside class="footnote brackets" id="proposal" role="doc-footnote"> <dt class="label" id="proposal">[<a href="#id5">5</a>]</dt> <dd><a class="reference external" href="https://mail.python.org/pipermail/python-3000/2007-April/007026.html">https://mail.python.org/pipermail/python-3000/2007-April/007026.html</a></aside> </aside> </section> <section id="copyright"> <h2><a class="toc-backref" href="#copyright" role="doc-backlink">Copyright</a></h2> <p>This document has been placed in the public domain.</p> </section> </section> <hr class="docutils" /> <p>Source: <a class="reference external" href="https://github.com/python/peps/blob/main/peps/pep-3133.rst">https://github.com/python/peps/blob/main/peps/pep-3133.rst</a></p> <p>Last modified: <a class="reference external" href="https://github.com/python/peps/commits/main/peps/pep-3133.rst">2023-09-09 17:39:29 GMT</a></p> </article> <nav id="pep-sidebar"> <h2>Contents</h2> <ul> <li><a class="reference internal" href="#rejection-notice">Rejection Notice</a></li> <li><a class="reference internal" href="#abstract">Abstract</a></li> <li><a class="reference internal" href="#rationale">Rationale</a><ul> <li><a class="reference internal" href="#a-note-on-syntax">A Note on Syntax</a></li> </ul> </li> <li><a class="reference internal" href="#performing-your-role">Performing Your Role</a><ul> <li><a class="reference internal" href="#static-role-assignment">Static Role Assignment</a></li> <li><a class="reference internal" href="#assigning-roles-at-runtime">Assigning Roles at Runtime</a></li> <li><a class="reference internal" href="#asking-questions-about-roles">Asking Questions About Roles</a></li> </ul> </li> <li><a class="reference internal" href="#defining-new-roles">Defining New Roles</a><ul> <li><a class="reference internal" href="#empty-roles">Empty Roles</a></li> <li><a class="reference internal" href="#composing-roles-via-inheritance">Composing Roles via Inheritance</a></li> <li><a class="reference internal" href="#requiring-concrete-methods">Requiring Concrete Methods</a></li> </ul> </li> <li><a class="reference internal" href="#mechanism">Mechanism</a></li> <li><a class="reference internal" href="#relationship-to-abstract-base-classes">Relationship to Abstract Base Classes</a></li> <li><a class="reference internal" href="#open-issues">Open Issues</a><ul> <li><a class="reference internal" href="#allowing-instances-to-perform-different-roles-than-their-class">Allowing Instances to Perform Different Roles Than Their Class</a></li> <li><a class="reference internal" href="#requiring-attributes">Requiring Attributes</a></li> <li><a class="reference internal" href="#roles-of-roles">Roles of Roles</a></li> <li><a class="reference internal" href="#class-performs">class_performs()</a></li> <li><a class="reference internal" href="#prettier-dynamic-role-assignment">Prettier Dynamic Role Assignment</a></li> <li><a class="reference internal" href="#syntax-support">Syntax Support</a></li> </ul> </li> <li><a class="reference internal" href="#implementation">Implementation</a></li> <li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li> <li><a class="reference internal" href="#references">References</a></li> <li><a class="reference internal" href="#copyright">Copyright</a></li> </ul> <br> <a id="source" href="https://github.com/python/peps/blob/main/peps/pep-3133.rst">Page Source (GitHub)</a> </nav> </section> <script src="../_static/colour_scheme.js"></script> <script src="../_static/wrap_tables.js"></script> <script src="../_static/sticky_banner.js"></script> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10