Python Forum
SQLAlchemy with type hints - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: SQLAlchemy with type hints (/thread-27697.html)



SQLAlchemy with type hints - gontajones - Jun-17-2020

Hey guys, I'm having hard time to make a clean type hint of an SQLAlchemy project that I'm working on.

The issue is that I need type hint for some methods that accept only a bunch of models from a file (eg models.py)

Something like this:
from typing import Union
from models import M1, M2, ..., M20

def func(table: Union[M1, M2, ..., M20]) -> bool
    ...
    return True
So this is getting too big and ugly Sad

Is it possible to get all classes from a file and insert them into the Union?
That way it would be more clean and even much more maintainable. Like:

from typing import Union
import models as m

def func(table: Union[model for model in dir(m)]) -> bool
    ...
    return True
This won't work as it is but is just the idea Wink


RE: SQLAlchemy with type hings - gontajones - Jun-17-2020

Just for future reference, what I decided to do was this:

models.py
from typing import Type, Union

TableTypes = Union[Type['M1'], Type['M2'], ..., Type['M20']]


class M1(db.Model):
    ...
class M2(db.Model):
    ...
...
class M20(db.Model):
    ...
Then wherever you need type hints you can use it like:
import models as m
 
def func(table: m.TableTypes) -> bool
    ...
    return True
Now it's more clean and mypy is not screaming anymore! =)