python - How can a runtime object type be used as a generic type hint parameter? -


introduction

with python/mypy type hints, 1 can use .pyi stubs keep annotations in separate files implementations. using functionality give basic hinting of sqlalchemy's orm (more specifically, flask_sqlalchemy plugin).

models defined like:

class mymodel(db.model):     id = db.column()     ... ... 

where db.model included directly sqlalchemy. can queried, example, by:

mymodel.query.filter({options: options}).one_or_none() 

where filter() returns query, , one_or_none() returns instance of mymodel (or none, obviously).

the follwoing .pyi file hints above construct, though incomplete - there no way hint return type of one_or_none().

class _sqlalchemy(sqlalchemy.orm.session.session):     class model:        query = ... # type: _query  class _query(sqlalchemy.orm.query.query):     def filter(self, *args) -> query.query: ...     def one_or_none(self) -> any: ...  db = ... # type: _sqlalchemy 

the question

how can 1 , generically hint above, , hint return type of one_or_none()? first attempt use generics, looks have no access the subtype in question (in given example, mymodel). illustrate nonworking approach:

from typing import generic, typevar  _t = typevar('_t')  class _sqlalchemy(sqlalchemy.orm.session.session):     class model:        def __init__(self, *args, **kwargs):            self.query = ... # type: _query[self.__class__]  class _query(generic[_t], sqlalchemy.orm.query.query):     def filter(self, *args) -> _query[_t]: ...     def one_or_none(self) -> _t: ...  db = ... # type: _sqlalchemy 

is there way working?

apologies specific , example, tried while write concisely generic example , never clear (which possibly still not much!)

edit

another non-working approach (i'm aware have limitation of having call mymodelinstance.query... instead of static mymodel.query, not work):

from typing import generic, typevar  _t = typevar('_t')  class _sqlalchemy(sqlalchemy.orm.session.session):     class model:         @property        def query(self: _t) -> _query[_t]: ...  class _query(generic[_t], sqlalchemy.orm.query.query):     def filter(self, *args) -> _query[_t]: ...     def one_or_none(self) -> _t: ...  db = ... # type: _sqlalchemy 


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -