Skip to content

Commit 155b537

Browse files
authored
Emulate generic types in runtime (#289)
* Emulate generic types in runtime * Fix flake8
1 parent de2df30 commit 155b537

2 files changed

Lines changed: 21 additions & 27 deletions

File tree

multidict/_abc.py

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,42 @@
11
import abc
22

3-
from typing import (Mapping, MutableMapping, List, Union, Iterable,
4-
TypeVar, Tuple, Dict, Optional)
3+
from collections.abc import Mapping, MutableMapping
54

65

7-
_T = TypeVar('_T')
6+
class _TypingMeta(abc.ABCMeta):
7+
# A fake metaclass to satisfy typing deps in runtime
8+
# basically MultiMapping[str] and other generic-like type instantiations
9+
# are emulated.
10+
# Note: real type hints are provided by __init__.pyi stub file
11+
def __getitem__(self, key):
12+
return self
813

9-
_D = TypeVar('_D')
1014

11-
12-
# Note: type defs are slightly different from __init__.pyi version The
13-
# correct one (and checked by mypy) is the later. Type checks here
14-
# exists for sake of consistency and allowing to instantiate
15-
# MultiMapiing[_T] in inline python code
16-
17-
18-
class MultiMapping(Mapping[str, _T]):
15+
class MultiMapping(Mapping, metaclass=_TypingMeta):
1916

2017
@abc.abstractmethod
21-
def getall(self, key: str,
22-
default: Optional[_D]=None) -> Union[List[_T], _D, None]:
18+
def getall(self, key, default=None):
2319
raise KeyError
2420

2521
@abc.abstractmethod
26-
def getone(self, key: str,
27-
default: Optional[_D]=None) -> Union[_T, _D, None]:
22+
def getone(self, key, default=None):
2823
raise KeyError
2924

3025

31-
_Arg = Union[Mapping[str, _T],
32-
Dict[str, _T],
33-
MultiMapping[_T],
34-
Iterable[Tuple[str, _T]]]
35-
36-
37-
class MutableMultiMapping(MultiMapping[_T], MutableMapping[str, _T]):
26+
class MutableMultiMapping(MultiMapping, MutableMapping):
3827

3928
@abc.abstractmethod
40-
def add(self, key: str, value: _T) -> None:
29+
def add(self, key, value):
4130
raise NotImplementedError
4231

4332
@abc.abstractmethod
44-
def extend(self, *args: _Arg[_T], **kwargs: _T) -> None:
33+
def extend(self, *args, **kwargs):
4534
raise NotImplementedError
4635

4736
@abc.abstractmethod
48-
def popone(self, key: str, default: Optional[_T]=None) -> _T:
37+
def popone(self, key, default=None):
4938
raise KeyError
5039

5140
@abc.abstractmethod
52-
def popall(self, key: str, default: Optional[_T]=None) -> List[_T]:
41+
def popall(self, key, default=None):
5342
raise KeyError

tests/test_abc.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,8 @@ def test_proxy_inheritance(proxy_classes):
157157
proxy, _ = proxy_classes
158158
assert issubclass(proxy, MultiMapping)
159159
assert not issubclass(proxy, MutableMultiMapping)
160+
161+
162+
def test_generic_type_in_runtime():
163+
MultiMapping[str]
164+
MutableMultiMapping[str]

0 commit comments

Comments
 (0)