As mentioned by kindall, a class decorator is a third option:
meta_attrs = ["alpha", "beta", "gamma"]
def decorate(klass):
for attr in meta_attrs:
setattr(klass, attr, attr.upper())
return klass
@decorate
class C(object):
pass
Here's a fourth option:
meta_attrs = ["alpha", "beta", "gamma"]
class C(object):
pass
for attr in meta_attrs:
setattr(C, attr, attr.upper())
I would go for a fifth option myself: Not having dynamic class attributes. I can't see the use case. If I really needed it, I'd probably use the fourth option, unless I needed it on more than one class, then I would use a decorator.
Metaclasses are often overly complicated, and the locals()
hack really is just an ugly trick and should be avoided.