What is considered an "advanced" topic in Python?

Jason Swails jason.swails at gmail.com
Fri May 29 17:28:43 EDT 2015


On Fri, May 29, 2015 at 5:06 PM, <sohcahtoa82 at gmail.com> wrote:

>
> > For example, the new (in 3.4) Enum class uses a metaclass.
> >
> >    class SomeEnum(Enum):
> >       first = 1
> >       second = 2
> >       third = 3
> >
> > The metaclass changes normal class behavior to:
> >
> >    - support iterating: list(SomeEnum) --> [SomeEnum.first,
> SomeEnum.second, SomeEnum.third]
> >    - support a length:  len(SomeEnum) --> 3
> >    - not allow new instances to be created:  --> SomeEnum(1) is
> SomeEnum(1)  # True
> >
> > --
> > ~Ethan~
>
> Regarding the first two, you can implement __iter__ and __len__ functions
> to create that functionality, though those functions would operate on an
> instance of the class, not the class itself.
>
> As for the third, can't you override the __new__ function to make attempts
> to create a new instance just return a previously created instance?
>

​Of course, but with metaclasses you don't *have* to (in fact, that's the
type of thing that the metaclass could do behind the scenes).

​In this case, any Enum subclass should *always* behave as Ethan described
-- without metaclasses that wouldn't necessarily be true (e.g., if the
person creating an Enum subclass didn't bother to correctly implement
__new__, __iter__, and __len__ for their subclass).

By using metaclasses, you can declare an Enum subclass as simply as Ethan
showed, since the metaclass does all of the dirty work implementing the
desired behavior at the time the class object is constructed (subclasses
inherit their parent class's metaclass).

In this use-case, you can think of it as a kind of "implicit class
factory".  Suppose you have a prescription for how you modify a class
definition (i.e., by implementing certain behavior in __new__ or __init__)
that you wrap up into some function "tweak_my_class".  The metaclass would
allow the class definition to be the equivalent of something like:

class MyClass(SubClass):
    # whatever

MyClass = tweak_my_class(MyClass)

Or as a class decorator

@tweak_my_class
class MyClass(SubClass):
    # whatever

(In fact, the `six` module allows you to implement metaclasses as
decorators to work with both Python 2 and Python 3, but I think metaclasses
are more powerful in Py3 than they are in Py2).​
​
They are cool ideas, and I've used them in my own code, but they do have a
kind of magic-ness to them -- especially in codes that you didn't write but
are working on.  As a result, I've recently started to prefer alternatives,
but in some rare cases (like Enum, for example), they are just the best
solution.

All the best,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150529/07ef4598/attachment.html>


More information about the Python-list mailing list