0

When browsing the source code for the django_filters library, I found a class declaration syntax that I've never seen before: inheritance with arguments. I could not find an explanation in the official python class tutorial.

Here is the source, snippet below:

class FilterSet(BaseFilterSet, metaclass=FilterSetMetaclass):
    pass

what does metaclass=FilterSetMetaclass in the class definition do?

NFern
  • 1,706
  • 17
  • 18

1 Answers1

2

There are two uses for keyword arguments in the list of base classes.

  1. The metaclass argument is used specially to indicate which metaclass (instead of type) to use to create the class. (In Python 2, this was done by assigning a value to the class attribute __metaclass__ in the body of the class statement.)

    A class statement is essentially a call to the metaclass.

    class Foo(metaclass=Bar):
        pass
    

    is equivalent to Foo = Bar('Foo', (), {}). The default metaclass is type, that is

    class Foo():
        pass
    

    is equivalent to

    class Foo(metaclass=type):
        pass
    
  2. Other keyword arguments are passed along to __init_subclass__.

Both of the above are simplifications; see Customizing Class creation for more details.

chepner
  • 497,756
  • 71
  • 530
  • 681