sqlalchemy-stubs icon indicating copy to clipboard operation
sqlalchemy-stubs copied to clipboard

Change JSON type from Dict to Mapping

Open whonore opened this issue 5 years ago • 3 comments

Would it be possible to make the type for JSON columns accept Mapping[str, Any] instead of (in addition to?) Dict[str, Any]? My specific use case is I have a fixed JSON schema that I represent with a TypedDict, but this is only compatible with Mapping, not Dict, so I have to either ignore the type or cast it when creating the column.

Even better would be if the plugin could somehow remember that it got a TypedDict and return that instead of a plain Dict or Mapping when you access the column later.

whonore avatar Jul 16 '19 22:07 whonore

We can consider this I think. In the meantime why wouldn't you just define your own type engine? For example:

from typing import TYPE_CHECKING, TypedDict

class User(TypedDict):
    id: int
    name: str

if TYPE_CHECKING:
    UserJSON = TypeEngine[User]
else:
    UserJSON = JSON

class Data(Base):
    user_data = Column(UserJSON, required=True)

data: Data
reveal_type(data.user_data['id'])  # Revealed type is "int"

ilevkivskyi avatar Jul 17 '19 09:07 ilevkivskyi

That seems like it probably would work for me, thanks.

whonore avatar Jul 17 '19 14:07 whonore

Also note that JSON columns can store a List as well.

bryanculbertson avatar Sep 17 '19 23:09 bryanculbertson