Style question: metaclass self vs cls?

S

Steven D'Aprano

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.

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

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?
 
T

Terry Reedy

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.)
 
M

Michele Simionato

The standard is to use `cls`. In the __new__ method you can use `mcl` or `meta`.
 
S

Steven D'Aprano

The standard is to use `cls`. In the __new__ method you can use `mcl` or
`meta`.

Thanks to everyone who answered.

I think I will stick with "meta" and "cls".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top