Home > Software design >  How do class declaration parameters work in python?
How do class declaration parameters work in python?

Time:03-26

Recently I came across SQLModel package. It combines pydantic and sqlalchemy features to work with database objects. What I noticed in documentation is that table=True parameter that you use to declare a model class:

from typing import Optional

from sqlmodel import Field, SQLModel, create_engine


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None

I could never understand what this kind of parameters is and how it works. How is it called and how can you implement one by your own? I have seen a metaclass keyword when declaring classes, but I thought there is a strict list of available keywords. But it seems like it's quite configurable.

This question is not directly related to SQLModel but rather to general python features.

Any information or links on this matter would be much appreciated.

CodePudding user response:

This behavior is based on the __init_subclass__ method that you can define in a class used as a metaclass. Look at the following example:

class MyMetaClass:
  def __init_subclass__(cls, foo=None):
    super().__init_subclass__()
    cls.foo = foo

class MyActualClass(MyMetaClass, foo='baz'):
  pass
  
instance = MyActualClass()
print(instance.foo)  # "baz"

You can find more details about this in the python official documentation: https://docs.python.org/3/reference/datamodel.html#customizing-class-creation

  • Related