Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve BaseFile typing #155

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion sqlalchemy_file/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import typing
from typing import Any
from typing import Any, Literal, overload, override

STR_ATTRS = Literal[
"url",
"filename",
"content_type",
"file_id",
"upload_storage",
"uploaded_at",
"path",
"url",
]
BOOL_ATTRS = Literal["saved"]
INT_ATTRS = Literal["size"]
DICT_ATTRS = Literal["meta_data"]
STR_LIST_ATTRS = Literal["files"]


class BaseFile(typing.Dict[str, Any]):
Expand All @@ -11,22 +26,65 @@ class BaseFile(typing.Dict[str, Any]):

"""

@overload
def __getitem__(self, key: STR_ATTRS) -> str:
...

@overload
def __getitem__(self, key: INT_ATTRS) -> int:
...

@overload
def __getitem__(self, key: DICT_ATTRS) -> dict[str, str]:
...

@overload
def __getitem__(self, key: STR_LIST_ATTRS) -> list[str]:
...

@overload
def __getitem__(self, key: BOOL_ATTRS) -> bool:
...

@override
def __getitem__(self, key: str) -> Any:
return dict.__getitem__(self, key)

@overload
def __getattr__(self, name: STR_ATTRS) -> str:
...

@overload
def __getattr__(self, name: INT_ATTRS) -> int:
...

@overload
def __getattr__(self, name: DICT_ATTRS) -> dict[str, str]:
...

@overload
def __getattr__(self, name: STR_LIST_ATTRS) -> list[str]:
...

@overload
def __getattr__(self, name: BOOL_ATTRS) -> bool:
...

def __getattr__(self, name: str) -> Any:
try:
return self[name]
except KeyError:
raise AttributeError(name)

@override
def __setitem__(self, key: str, value: Any) -> None:
if getattr(self, "_frozen", False):
raise TypeError("Already saved files are immutable")
return dict.__setitem__(self, key, value)

__setattr__ = __setitem__

@override
def __delattr__(self, name: str) -> None:
if getattr(self, "_frozen", False):
raise TypeError("Already saved files are immutable")
Expand All @@ -36,6 +94,7 @@ def __delattr__(self, name: str) -> None:
except KeyError:
raise AttributeError(name)

@override
def __delitem__(self, key: str) -> None:
if object.__getattribute__(self, "_frozen"):
raise TypeError("Already saved files are immutable")
Expand Down
Loading