0

Consider this code:

from sqlmodel import SQLModel, Field

class Task(SQLModel, table=True):

    id = Column(Integer, primary_key=True, index=True)

I only stepped away from python for a few weeks and now there are arguments in the class-inheritance brackets? What does this do, how do I do it and are there drawbacks/benefits? Whats it called? Once I know what its called I can look it up.

EDIT: This is not a typo, this code works as is.

Cygnuson
  • 160
  • 1
  • 11
  • If you want to use as arguments, you should use as `task = Task(table=True)` – Javohir Elmurodov Jan 12 '23 at 06:25
  • This code works as is and I just want to know why and how to make a class that does it. – Cygnuson Jan 12 '23 at 06:26
  • 2
    Check this question https://stackoverflow.com/questions/13762231/how-to-pass-arguments-to-the-metaclass-from-the-class-definition – Javohir Elmurodov Jan 12 '23 at 06:58
  • nice thanks @JavohirElmurodov! Found this too https://stackoverflow.com/questions/45400284/understanding-init-subclass – Cygnuson Jan 12 '23 at 07:14
  • In this case it really is the metaclass though, as @JavohirElmurodov suggested. The `table` keyword argument is first picked up by `SQLModelMetaclass.__new__` [here](https://github.com/tiangolo/sqlmodel/blob/0.0.8/sqlmodel/main.py#L288) and then assigned to the new class' `__config__` attribute. It is then later used during the metaclass' `__init__` and even later in the actual class `__init__`. – Daniil Fajnberg Jan 16 '23 at 21:46

1 Answers1

0

Short answer

table=True is the attribute that the class SQLModel uses to distinguish if something is a Pydantic model or an SQLAlchemy model.

Long answer

Not that long .. but here is the class and here is where the check happens. There is more to it, but basically, it is to distinguish if it should be a Pydantic model or an SQLAlchemy model.

  • Im not sure, but If I did this: `class MyClass(someVar=True): ... ` How do I access `someVar` from within the class? Can it even be done? What is this even called and how do I find out more? – Cygnuson Jan 12 '23 at 07:05
  • Hmmm... it looks like (from your second link) its in the `cls.__config__` where `cls` is used instead of `self` – Cygnuson Jan 12 '23 at 07:09
  • `getattr(cls.__config__, "someVar")` – enslaved_programmer Jan 12 '23 at 07:09
  • found it , its part of __init_subclass__ https://stackoverflow.com/questions/45400284/understanding-init-subclass – Cygnuson Jan 12 '23 at 07:13
  • Does the above answer, answer your question about `table=True`? – enslaved_programmer Jan 12 '23 at 07:19
  • Technically, the code passages you linked do not show, where the keyword argument is actually picked up. This happens in the metaclass' `__new__` method, as soon as the subclass created. But the explanation of the purpose is correct. – Daniil Fajnberg Jan 16 '23 at 21:49