Search code examples
pythondjangoclass-method

Django classmethod doesn't have a decorator


I saw a couple of classmethod that doesn't have a decorator @classmethod. What's the reason about it?

https://github.com/django/django/blob/3.0/django/db/models/base.py#L320

enter image description here

https://github.com/django/django/blob/3.0/django/db/models/manager.py#L20

enter image description here


Solution

  • The items over which you talk about are used as metaclasses [Python-doc]. One could say that a meta-class is the type of the type. If we for example take a look at the ModelBase soure code [GitHub], we see:

    class ModelBase(type):
        """Metaclass for all models."""
        def __new__(cls, name, bases, attrs, **kwargs):
            super_new = super().__new__
    
        # …

    It thus inherits from type, which is the basic base class of meta-classes.

    Here the "self" object is thus the the class itself that is analyzed, updated, etc. While one does not per se needs to use cls, it is common that in meta-classes what would be the self of an ordinary class, is named cls in a meta-class definition, to stress the fact that is the class object itself that we are manipulating.