2

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.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Artem Ilin
  • 353
  • 2
  • 19

1 Answers1

3

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

Erick Hupin
  • 162
  • 7
  • Is is also passed to the metaclass' `__new__` and `__init__` methods - not only to `__init_subclass__`. – jsbueno Mar 26 '22 at 17:22