Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I somehow reference a Python class that is declared later than the class from which I need to reference without changing their order?

I have these two Python classes(Pydantic schemas which represent SQLAlchemy models):

class Role(RoleBase):
    id: int
    users: list[User] = []

    class Config:
        orm_mode = True

class User(UserBase):
    id: int
    date_created: datetime.datetime
    profile_image: Optional[str] = None

    class Config:
        orm_mode = True

I’ve tried to do it with ForwardRef:

User = ForwardRef('User')
...
users: list[User] = []

or to wrap it with quotes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

users: List['User'] = []

but I get TypeError: issubclass() arg 1 must be a class.

Is there some way to implement this without changing classes’ declaration order?

>Solution :

When using pydantic.ForwardRef, you need to call update_forward_refs on classes that have forward references to update them. So add

Role.update_forward_refs()

after User is defined.

This will all be unnecessary if PEP 649 is accepted.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading