Skip to content

Commit 3aa8fe8

Browse files
ArneGudermannphorwardsveneberth
committed
refactor: Improved type annotations (#986)
Mostly replaced `typing` by `t` Resolve the typing part of #958 --------- Co-authored-by: Jan Max Meyer <[email protected]> Co-authored-by: Sven Eberth <[email protected]>
1 parent 16f5a88 commit 3aa8fe8

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+420
-419
lines changed

src/viur/core/__init__.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
import inspect
3535
import warnings
3636
from types import ModuleType
37-
from typing import Callable, Dict, Union, List
37+
import typing as t
3838
from google.appengine.api import wrap_wsgi_app
3939
import yaml
4040
from viur.core import i18n, request, utils
@@ -84,7 +84,8 @@
8484
# Show DeprecationWarning from the viur-core
8585
warnings.filterwarnings("always", category=DeprecationWarning, module=r"viur\.core.*")
8686

87-
def load_indexes_from_file() -> Dict[str, List]:
87+
88+
def load_indexes_from_file() -> dict[str, list]:
8889
"""
8990
Loads all indexes from the index.yaml and stores it in a dictionary sorted by the module(kind)
9091
:return A dictionary of indexes per module
@@ -127,7 +128,7 @@ def setDefaultDomainLanguage(domain: str, lang: str):
127128
conf.i18n.domain_language_mapping[host] = lang.lower()
128129

129130

130-
def buildApp(modules: Union[ModuleType, object], renderers: Union[ModuleType, Dict], default: str = None) -> Module:
131+
def buildApp(modules: ModuleType | object, renderers: ModuleType | object, default: str = None) -> Module:
131132
"""
132133
Creates the application-context for the current instance.
133134
@@ -234,7 +235,7 @@ def buildApp(modules: Union[ModuleType, object], renderers: Union[ModuleType, Di
234235
return root
235236

236237

237-
def setup(modules: Union[object, ModuleType], render: Union[ModuleType, Dict] = None, default: str = "html"):
238+
def setup(modules: ModuleType | object, render: ModuleType | object = None, default: str = "html"):
238239
"""
239240
Define whats going to be served by this instance.
240241
@@ -310,7 +311,7 @@ def setup(modules: Union[object, ModuleType], render: Union[ModuleType, Dict] =
310311
return wrap_wsgi_app(app)
311312

312313

313-
def app(environ: dict, start_response: Callable):
314+
def app(environ: dict, start_response: t.Callable):
314315
return request.Router(environ).response(environ, start_response)
315316

316317

src/viur/core/bones/base.py

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from dataclasses import dataclass, field
1313
from datetime import datetime, timedelta
1414
from enum import Enum
15-
from typing import Any, Dict, Iterator, List, Optional, Set, Tuple, Union
15+
import typing as t
1616

1717
from viur.core import db, utils
1818
from viur.core.config import conf
@@ -76,9 +76,9 @@ class ReadFromClientError:
7676
"""A ReadFromClientErrorSeverity enumeration value representing the severity of the error."""
7777
errorMessage: str
7878
"""A string containing a human-readable error message describing the issue."""
79-
fieldPath: List[str] = field(default_factory=list)
79+
fieldPath: list[str] = field(default_factory=list)
8080
"""A list of strings representing the path to the field where the error occurred."""
81-
invalidatedFields: List[str] = None
81+
invalidatedFields: list[str] = None
8282
"""A list of strings containing the names of invalidated fields, if any."""
8383

8484

@@ -192,18 +192,18 @@ def __init__(
192192
self,
193193
*,
194194
compute: Compute = None,
195-
defaultValue: Any = None,
195+
defaultValue: t.Any = None,
196196
descr: str = "",
197197
getEmptyValueFunc: callable = None,
198198
indexed: bool = True,
199199
isEmptyFunc: callable = None, # fixme: Rename this, see below.
200-
languages: Union[None, List[str]] = None,
201-
multiple: Union[bool, MultipleConstraints] = False,
202-
params: Dict = None,
200+
languages: None | list[str] = None,
201+
multiple: bool | MultipleConstraints = False,
202+
params: dict = None,
203203
readOnly: bool = None, # fixme: Rename into readonly (all lowercase!) soon.
204-
required: Union[bool, List[str], Tuple[str]] = False,
204+
required: bool | list[str] | tuple[str] = False,
205205
searchable: bool = False,
206-
unique: Union[None, UniqueValue] = None,
206+
unique: None | UniqueValue = None,
207207
vfunc: callable = None, # fixme: Rename this, see below.
208208
visible: bool = True,
209209
):
@@ -306,7 +306,7 @@ def isInvalid(self, value):
306306
"""
307307
return False
308308

309-
def isEmpty(self, value: Any) -> bool:
309+
def isEmpty(self, value: t.Any) -> bool:
310310
"""
311311
Check if the given single value represents the "empty" value.
312312
This usually is the empty string, 0 or False.
@@ -339,7 +339,7 @@ def getDefaultValue(self, skeletonInstance):
339339
else:
340340
return self.defaultValue
341341

342-
def getEmptyValue(self) -> Any:
342+
def getEmptyValue(self) -> t.Any:
343343
"""
344344
Returns the value representing an empty field for this bone.
345345
This might be the empty string for str/text Bones, Zero for numeric bones etc.
@@ -482,9 +482,9 @@ def parseSubfieldsFromClient(self) -> bool:
482482
"""
483483
return False
484484

485-
def singleValueFromClient(self, value: Any, skel: 'SkeletonInstance',
485+
def singleValueFromClient(self, value: t.Any, skel: 'SkeletonInstance',
486486
bone_name: str, client_data: dict
487-
) -> tuple[Any, list[ReadFromClientError] | None]:
487+
) -> tuple[t.Any, list[ReadFromClientError] | None]:
488488
"""Load a single value from a client
489489
490490
:param value: The single value which should be loaded.
@@ -501,7 +501,7 @@ def singleValueFromClient(self, value: Any, skel: 'SkeletonInstance',
501501
return self.getEmptyValue(), [
502502
ReadFromClientError(ReadFromClientErrorSeverity.Invalid, "Will not read a BaseBone fromClient!")]
503503

504-
def fromClient(self, skel: 'SkeletonInstance', name: str, data: dict) -> Union[None, List[ReadFromClientError]]:
504+
def fromClient(self, skel: 'SkeletonInstance', name: str, data: dict) -> None | list[ReadFromClientError]:
505505
"""
506506
Reads a value from the client and stores it in the skeleton instance if it is valid for the bone.
507507
@@ -586,7 +586,7 @@ def fromClient(self, skel: 'SkeletonInstance', name: str, data: dict) -> Union[N
586586
errors.extend(self.validateMultipleConstraints(skel, name))
587587
return errors or None
588588

589-
def validateMultipleConstraints(self, skel: 'SkeletonInstance', name: str) -> List[ReadFromClientError]:
589+
def validateMultipleConstraints(self, skel: 'SkeletonInstance', name: str) -> list[ReadFromClientError]:
590590
"""
591591
Validates the value of a bone against its multiple constraints and returns a list of ReadFromClientError
592592
objects for each violation, such as too many items or duplicates.
@@ -844,8 +844,8 @@ def buildDBFilter(self,
844844
name: str,
845845
skel: 'viur.core.skeleton.SkeletonInstance',
846846
dbFilter: db.Query,
847-
rawFilter: Dict,
848-
prefix: Optional[str] = None) -> db.Query:
847+
rawFilter: dict,
848+
prefix: t.Optional[str] = None) -> db.Query:
849849
"""
850850
Parses the searchfilter a client specified in his Request into
851851
something understood by the datastore.
@@ -896,7 +896,7 @@ def buildDBSort(self,
896896
name: str,
897897
skel: 'viur.core.skeleton.SkeletonInstance',
898898
dbFilter: db.Query,
899-
rawFilter: Dict) -> Optional[db.Query]:
899+
rawFilter: dict) -> t.Optional[db.Query]:
900900
"""
901901
Same as buildDBFilter, but this time its not about filtering
902902
the results, but by sorting them.
@@ -945,7 +945,7 @@ def buildDBSort(self,
945945
dbFilter.order(order)
946946
return dbFilter
947947

948-
def _hashValueForUniquePropertyIndex(self, value: Union[str, int]) -> List[str]:
948+
def _hashValueForUniquePropertyIndex(self, value: str | int) -> list[str]:
949949
"""
950950
Generates a hash of the given value for creating unique property indexes.
951951
@@ -958,7 +958,7 @@ def _hashValueForUniquePropertyIndex(self, value: Union[str, int]) -> List[str]:
958958
:return: A list containing a string representation of the hashed value. If the bone is multiple,
959959
the list may contain more than one hashed value.
960960
"""
961-
def hashValue(value: Union[str, int]) -> str:
961+
def hashValue(value: str | int) -> str:
962962
h = hashlib.sha256()
963963
h.update(str(value).encode("UTF-8"))
964964
res = h.hexdigest()
@@ -994,7 +994,7 @@ def keyHash(key):
994994
# Lock the value for that specific list
995995
return [hashValue(", ".join(tmpList))]
996996

997-
def getUniquePropertyIndexValues(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) -> List[str]:
997+
def getUniquePropertyIndexValues(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) -> list[str]:
998998
"""
999999
Returns a list of hashes for the current value(s) of a bone in the skeleton, used for storing in the
10001000
unique property value index.
@@ -1011,13 +1011,13 @@ def getUniquePropertyIndexValues(self, skel: 'viur.core.skeleton.SkeletonInstanc
10111011
return []
10121012
return self._hashValueForUniquePropertyIndex(val)
10131013

1014-
def getReferencedBlobs(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) -> Set[str]:
1014+
def getReferencedBlobs(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) -> set[str]:
10151015
"""
10161016
Returns a set of blob keys referenced from this bone
10171017
"""
10181018
return set()
10191019

1020-
def performMagic(self, valuesCache: Dict, name: str, isAdd: bool):
1020+
def performMagic(self, valuesCache: dict, name: str, isAdd: bool):
10211021
"""
10221022
This function applies "magically" functionality which f.e. inserts the current Date
10231023
or the current user.
@@ -1051,7 +1051,7 @@ def refresh(self, skel: 'viur.core.skeleton.SkeletonInstance', boneName: str) ->
10511051
"""
10521052
pass
10531053

1054-
def mergeFrom(self, valuesCache: Dict, boneName: str, otherSkel: 'viur.core.skeleton.SkeletonInstance'):
1054+
def mergeFrom(self, valuesCache: dict, boneName: str, otherSkel: 'viur.core.skeleton.SkeletonInstance'):
10551055
"""
10561056
Merges the values from another skeleton instance into the current instance, given that the bone types match.
10571057
@@ -1076,9 +1076,9 @@ def mergeFrom(self, valuesCache: Dict, boneName: str, otherSkel: 'viur.core.skel
10761076
def setBoneValue(self,
10771077
skel: 'SkeletonInstance',
10781078
boneName: str,
1079-
value: Any,
1079+
value: t.Any,
10801080
append: bool,
1081-
language: Union[None, str] = None) -> bool:
1081+
language: None | str = None) -> bool:
10821082
"""
10831083
Sets the value of a bone in a skeleton instance, with optional support for appending and language-specific
10841084
values. Sanity checks are being performed.
@@ -1132,7 +1132,7 @@ def setBoneValue(self,
11321132
skel[boneName][language] = val
11331133
return True
11341134

1135-
def getSearchTags(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) -> Set[str]:
1135+
def getSearchTags(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) -> set[str]:
11361136
"""
11371137
Returns a set of strings as search index for this bone.
11381138
@@ -1150,7 +1150,7 @@ def getSearchTags(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str)
11501150

11511151
def iter_bone_value(
11521152
self, skel: 'viur.core.skeleton.SkeletonInstance', name: str
1153-
) -> Iterator[Tuple[Optional[int], Optional[str], Any]]:
1153+
) -> t.Iterator[tuple[t.Optional[int], t.Optional[str], t.Any]]:
11541154
"""
11551155
Yield all values from the Skeleton related to this bone instance.
11561156

src/viur/core/bones/boolean.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, List, Optional, Union
1+
import typing as t
22

33
from viur.core import conf, db, utils
44
from viur.core.bones.base import BaseBone
@@ -18,11 +18,7 @@ class BooleanBone(BaseBone):
1818
def __init__(
1919
self,
2020
*,
21-
defaultValue: Union[
22-
bool,
23-
List[bool],
24-
Dict[str, Union[List[bool], bool]],
25-
] = None,
21+
defaultValue: bool | list[bool] | dict[str, list[bool] | bool] = None,
2622
**kwargs
2723
):
2824
if defaultValue is None:
@@ -56,7 +52,7 @@ def getEmptyValue(self):
5652
"""
5753
return False
5854

59-
def isEmpty(self, value: Any):
55+
def isEmpty(self, value: t.Any):
6056
"""
6157
Checks if the given boolean value is empty.
6258
@@ -85,8 +81,8 @@ def buildDBFilter(
8581
name: str,
8682
skel: 'viur.core.skeleton.SkeletonInstance',
8783
dbFilter: db.Query,
88-
rawFilter: Dict,
89-
prefix: Optional[str] = None
84+
rawFilter: dict,
85+
prefix: t.Optional[str] = None
9086
) -> db.Query:
9187
"""
9288
Builds a database filter based on the boolean value.

src/viur/core/bones/captcha.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22
import urllib.parse
33
import urllib.request
4-
from typing import List, Union
4+
import typing as t
55

66
from viur.core import conf, current
77
from viur.core.bones.base import BaseBone, ReadFromClientError, ReadFromClientErrorSeverity
@@ -49,7 +49,7 @@ def unserialize(self, skel, name) -> bool:
4949
skel.accessedValues[name] = self.publicKey
5050
return True
5151

52-
def fromClient(self, skel: 'SkeletonInstance', name: str, data: dict) -> Union[None, List[ReadFromClientError]]:
52+
def fromClient(self, skel: 'SkeletonInstance', name: str, data: dict) -> None | list[ReadFromClientError]:
5353
"""
5454
Reads a value from the client.
5555
If this value is valid for this bone,

src/viur/core/bones/date.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from datetime import datetime, timedelta, timezone
2-
from typing import Dict, Optional
2+
import typing as t
33

44
import pytz
55
import tzlocal
@@ -316,8 +316,8 @@ def buildDBFilter(self,
316316
name: str,
317317
skel: 'viur.core.skeleton.SkeletonInstance',
318318
dbFilter: db.Query,
319-
rawFilter: Dict,
320-
prefix: Optional[str] = None) -> db.Query:
319+
rawFilter: dict,
320+
prefix: t.Optional[str] = None) -> db.Query:
321321
"""
322322
Constructs a datastore filter for date and/or time values based on the given raw filter. It parses the
323323
raw filter and, if successful, applies it to the datastore query.

src/viur/core/bones/file.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
from hashlib import sha256
99
from time import time
10-
from typing import Any, Dict, List, Set, Union
10+
import typing as t
1111
from viur.core import conf, db
1212
from viur.core.bones.treeleaf import TreeLeafBone
1313
from viur.core.tasks import CallDeferred
@@ -16,15 +16,15 @@
1616

1717

1818
@CallDeferred
19-
def ensureDerived(key: db.Key, srcKey, deriveMap: Dict[str, Any], refreshKey: db.Key = None):
19+
def ensureDerived(key: db.Key, srcKey, deriveMap: dict[str, t.Any], refreshKey: db.Key = None):
2020
r"""
2121
The function is a deferred function that ensures all pending thumbnails or other derived files
2222
are built. It takes the following parameters:
2323
2424
:param db.key key: The database key of the file-object that needs to have its derivation map
2525
updated.
2626
:param str srcKey: A prefix for a stable key to prevent rebuilding derived files repeatedly.
27-
:param Dict[str,Any] deriveMap: A list of DeriveDicts that need to be built or updated.
27+
:param dict[str,Any] deriveMap: A list of DeriveDicts that need to be built or updated.
2828
:param db.Key refreshKey: If set, the function fetches and refreshes the skeleton after
2929
building new derived files.
3030
@@ -139,9 +139,9 @@ class FileBone(TreeLeafBone):
139139
def __init__(
140140
self,
141141
*,
142-
derive: Union[None, Dict[str, Any]] = None,
143-
maxFileSize: Union[None, int] = None,
144-
validMimeTypes: Union[None, List[str]] = None,
142+
derive: None | dict[str, t.Any] = None,
143+
maxFileSize: None | int = None,
144+
validMimeTypes: None | list[str] = None,
145145
**kwargs
146146
):
147147
r"""
@@ -231,7 +231,7 @@ def handleDerives(values):
231231
else:
232232
handleDerives(values)
233233

234-
def getReferencedBlobs(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) -> Set[str]:
234+
def getReferencedBlobs(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) -> set[str]:
235235
r"""
236236
Retrieves the referenced blobs in the FileBone.
237237

src/viur/core/bones/json.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import ast
22
import json
3-
from typing import Mapping, Union
3+
import typing as t
44

55
import jsonschema
66

@@ -23,7 +23,7 @@ class JsonBone(RawBone):
2323

2424
type = "raw.json"
2525

26-
def __init__(self, indexed: bool = False, multiple: bool = False, languages: bool = None, schema: Mapping = {},
26+
def __init__(self, indexed: bool = False, multiple: bool = False, languages: bool = None, schema: t.Mapping = {},
2727
*args,
2828
**kwargs):
2929
super().__init__(*args, **kwargs)
@@ -52,7 +52,7 @@ def unserialize(self, skel: 'viur.core.skeleton.SkeletonInstance', name: str) ->
5252

5353
return False
5454

55-
def singleValueFromClient(self, value: Union[str, list, dict], skel, bone_name, client_data):
55+
def singleValueFromClient(self, value: str | list | dict, skel, bone_name, client_data):
5656
if value:
5757
if not isinstance(value, (list, dict)):
5858
value = str(value)

0 commit comments

Comments
 (0)