Skip to content

Commit 02782c2

Browse files
Initial mypy setup (#560)
1 parent a274196 commit 02782c2

26 files changed

+91
-50
lines changed

.github/workflows/ci.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ jobs:
114114
env:
115115
COLOR: 'yes'
116116
run: |
117-
pytest tests
117+
pytest tests --cov-report xml --cov-report html
118118
python -m coverage xml
119119
- name: Run functional tests
120120
run: bash examples/run_all.sh

.mypy.ini

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
[mypy]
2+
files = aiocache, examples, tests
3+
#check_untyped_defs = True
4+
follow_imports_for_stubs = True
5+
#disallow_any_decorated = True
6+
disallow_any_generics = True
7+
disallow_incomplete_defs = True
8+
disallow_subclassing_any = True
9+
#disallow_untyped_calls = True
10+
disallow_untyped_decorators = True
11+
#disallow_untyped_defs = True
12+
implicit_reexport = False
13+
no_implicit_optional = True
14+
show_error_codes = True
15+
strict_equality = True
16+
warn_incomplete_stub = True
17+
warn_redundant_casts = True
18+
warn_unreachable = True
19+
warn_unused_ignores = True
20+
disallow_any_unimported = True
21+
#warn_return_any = True
22+
23+
[mypy-tests.*]
24+
disallow_any_decorated = False
25+
disallow_untyped_calls = False
26+
disallow_untyped_defs = False
27+
28+
29+
[mypy-msgpack.*]
30+
ignore_missing_imports = True

aiocache/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import logging
2+
from typing import Dict, Type
23

34
from ._version import __version__
45
from .backends.memory import SimpleMemoryCache
6+
from .base import BaseCache
57

68
logger = logging.getLogger(__name__)
79

8-
AIOCACHE_CACHES = {SimpleMemoryCache.NAME: SimpleMemoryCache}
10+
AIOCACHE_CACHES: Dict[str, Type[BaseCache]] = {SimpleMemoryCache.NAME: SimpleMemoryCache}
911

1012
try:
1113
import aioredis

aiocache/backends/memory.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
from typing import Dict
23

34
from aiocache.base import BaseCache
45
from aiocache.serializers import NullSerializer
@@ -9,8 +10,8 @@ class SimpleMemoryBackend:
910
Wrapper around dict operations to use it as a cache backend
1011
"""
1112

12-
_cache = {}
13-
_handlers = {}
13+
_cache: Dict[str, object] = {}
14+
_handlers: Dict[str, asyncio.TimerHandle] = {}
1415

1516
def __init__(self, **kwargs):
1617
super().__init__(**kwargs)

aiocache/backends/redis.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,6 @@ class RedisBackend:
4646
" end"
4747
)
4848

49-
pools = {}
50-
5149
def __init__(
5250
self,
5351
endpoint="127.0.0.1",

aiocache/base.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44
import os
55
import time
6+
from typing import Callable, Set
67

78
from aiocache import serializers
89

@@ -14,7 +15,7 @@
1415

1516
class API:
1617

17-
CMDS = set()
18+
CMDS: Set[Callable[..., object]] = set()
1819

1920
@classmethod
2021
def register(cls, func):
@@ -103,6 +104,8 @@ class BaseCache:
103104
the backend. It can be overriden in the specific calls.
104105
"""
105106

107+
NAME: str
108+
106109
def __init__(
107110
self, serializer=None, plugins=None, namespace=None, key_builder=None, timeout=5, ttl=None
108111
):

aiocache/factory.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import urllib
33
import warnings
44
from copy import deepcopy
5+
from typing import Dict
56

67
from aiocache import AIOCACHE_CACHES
78
from aiocache.base import BaseCache
@@ -126,7 +127,7 @@ def from_url(cls, url):
126127

127128
class CacheHandler:
128129

129-
_config = {
130+
_config: Dict[str, Dict[str, object]] = {
130131
"default": {
131132
"cache": "aiocache.SimpleMemoryCache",
132133
"serializer": {"class": "aiocache.serializers.StringSerializer"},
@@ -136,7 +137,7 @@ class CacheHandler:
136137
def __init__(self):
137138
self._caches = {}
138139

139-
def add(self, alias: str, config: dict) -> None:
140+
def add(self, alias: str, config: Dict[str, object]) -> None:
140141
"""
141142
Add a cache to the current config. If the key already exists, it
142143
will overwrite it::
@@ -153,7 +154,7 @@ def add(self, alias: str, config: dict) -> None:
153154
"""
154155
self._config[alias] = config
155156

156-
def get(self, alias: str):
157+
def get(self, alias: str) -> object:
157158
"""
158159
Retrieve cache identified by alias. Will return always the same instance
159160

aiocache/lock.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import asyncio
22
import uuid
3-
from typing import Any, Union
3+
from typing import Any, Dict, Union
44

55
from aiocache.base import BaseCache
66

@@ -60,7 +60,7 @@ class RedLock:
6060
result of ``super_expensive_function``.
6161
"""
6262

63-
_EVENTS = {}
63+
_EVENTS: Dict[str, asyncio.Event] = {}
6464

6565
def __init__(self, client: BaseCache, key: str, lease: Union[int, float]):
6666
self.client = client
@@ -149,7 +149,7 @@ async def _acquire(self):
149149
async def __aexit__(self, exc_type, exc_value, traceback):
150150
pass
151151

152-
async def cas(self, value: Any, **kwargs) -> bool:
152+
async def cas(self, value: Any, **kwargs: Any) -> bool:
153153
"""
154154
Checks and sets the specified value for the locked key. If the value has changed
155155
since the lock was created, it will raise an :class:`aiocache.lock.OptimisticLockError`

aiocache/py.typed

Whitespace-only changes.

aiocache/serializers/serializers.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import logging
22
import pickle # noqa: S403
3+
from typing import Any, Optional
34

45
logger = logging.getLogger(__name__)
56

67
try:
78
import ujson as json
89
except ImportError:
910
logger.debug("ujson module not found, using json")
10-
import json
11+
import json # type: ignore[no-redef]
1112

1213
try:
1314
import msgpack
@@ -21,16 +22,18 @@
2122

2223
class BaseSerializer:
2324

24-
DEFAULT_ENCODING = "utf-8"
25+
DEFAULT_ENCODING: Optional[str] = "utf-8"
2526

2627
def __init__(self, *args, encoding=_NOT_SET, **kwargs):
2728
self.encoding = self.DEFAULT_ENCODING if encoding is _NOT_SET else encoding
2829
super().__init__(*args, **kwargs)
2930

30-
def dumps(self, value):
31+
# TODO(PY38): Positional-only
32+
def dumps(self, value: Any) -> str:
3133
raise NotImplementedError("dumps method must be implemented")
3234

33-
def loads(self, value):
35+
# TODO(PY38): Positional-only
36+
def loads(self, value: str) -> Any:
3437
raise NotImplementedError("loads method must be implemented")
3538

3639

0 commit comments

Comments
 (0)