On 7/16/2012 11:29 AM, Steven D'Aprano wrote:
Here's a style question for you: in a metaclass, what should I call the
instance parameter of methods, "cls" or "self"?

class ExampleMeta(type):
     def method(self, *args): ...

I'm not quite sure if that feels right. On the one hand, self is the
ExampleMeta instance alright... but on the other, self is actually a
class, so I feel I want to call it "cls" rather than "self", which makes
it more obvious that you're looking at a metaclass.

I have never seriously written a metaclass, but as a reader I would prefer 'cls'.

On the third-hand, it may be confusing that the argument is called "cls"
but not decorated with classdecorator.

To me, that reinforces 'looking as a metaclass'.

An @classmethod in a class is a class method specific to the particular class. A method in a metaclass is a method common to all classes of the metaclass. They could be written differently, yet calling the first param 'cls' either way seems reasonable.

I'm very slightly leaning towards writing metaclasses like this:

class ExampleMeta(type):
     def __new__(meta, *args): ...
     def method(cls, *args): ...

class Example(metaclass=ExampleMeta):
     def another_method(self): ...

What do others do?

Not too many people write real metaclasses. Python lets you chose. Have you looked at the C code of type? (Not that you are bound by it.)

--
Terry Jan Reedy



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to