Python Forum

Full Version: SQLAlchemy with type hints
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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! =)