Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting a class' metaclass using a decorator
    primarykey
    data
    text
    <p>Following <a href="https://stackoverflow.com/a/5121381/623518">this answer</a> it seems that a class' metaclass may be changed after the class has been defined by using the following*:</p> <pre><code>class MyMetaClass(type): # Metaclass magic... class A(object): pass A = MyMetaClass(A.__name__, A.__bases__, dict(A.__dict__)) </code></pre> <p>Defining a function</p> <pre><code>def metaclass_wrapper(cls): return MyMetaClass(cls.__name__, cls.__bases__, dict(cls.__dict__)) </code></pre> <p>allows me to apply a decorator to a class definition like so,</p> <pre><code>@metaclass_wrapper class B(object): pass </code></pre> <p>It seems that the metaclass magic is applied to <code>B</code>, however <code>B</code> has no <code>__metaclass__</code> attribute. Is the above method a sensible way to apply metaclasses to class definitions, even though I am definiting and re-definiting a class, or would I be better off simply writing</p> <pre><code>class B(object): __metaclass__ = MyMetaClass pass </code></pre> <p>I presume there are some differences between the two methods.</p> <hr> <p>*Note, the original answer in the linked question, <code>MyMetaClass(A.__name__, A.__bases__, A.__dict__)</code>, returns a <code>TypeError</code>:</p> <blockquote> <p>TypeError: type() argument 3 must be a dict, not dict_proxy</p> </blockquote> <p>It seems that the <code>__dict__</code> attribute of <code>A</code> (the class definition) has a type <code>dict_proxy</code>, whereas the type of the <code>__dict__</code> attribute of an <em>instance</em> of <code>A</code> has a type <code>dict</code>. Why is this? Is this a Python 2.x vs. 3.x difference?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload