[Tutor] question about metaclasses

Zachary Ware zachary.ware+pytut at gmail.com
Wed Jan 10 13:08:39 EST 2018


On Wed, Jan 10, 2018 at 10:08 AM, Albert-Jan Roskam
<sjeik_appie at hotmail.com> wrote:
> Hi,
>
>
> In another thread on this list I was reminded of types.SimpleNamespace. This is nice, but I wanted to create a bag class with constants that are read-only. My main question is about example #3 below (example #2 just illustrates my thought process). Is this a use case to a metaclass? Or can I do it some other way (maybe a class decorator?). I would like to create a metaclass that converts any non-special attributes (=not starting with '_') into properties, if needed. That way I can specify my bag class in a very clean way: I only specify the metaclass, and I list the attributes as normal attrbutes, because the metaclass will convert them into properties.

You appear to be reimplementing Enum.

> Why does following the line (in #3) not convert the normal attribute into a property?
>
> setattr(cls, attr, property(lambda self: obj))  # incorrect!

Because `cls` is `Meta`, not `MyReadOnlyConst`; `__new__` is
implicitly a classmethod and `MyReadOnlyConst` doesn't actually exist
yet.  When `MyReadOnlyConst` is created by `type.__new__` it will be
filled with the contents of `attrs`, so instead of `setattr` you want
`attrs[attr] = property(...)`.

But once you're past the learning exercise that this is, just use
enum.Enum or collections.namedtuple :)

-- 
Zach


More information about the Tutor mailing list