Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SQLAlchemy with type hints
#1
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
Reply
#2
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! =)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Type hints and style MaxPowers 1 519 Feb-19-2020, 06:56 PM
Last Post: micseydel
  Type hinting - return type based on parameter micseydel 2 582 Jan-14-2020, 01:20 AM
Last Post: micseydel
  Should a function ever be more permissive than its type hints? Shay 1 549 Mar-13-2019, 05:36 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020