def test_generic_class_with_two_typeargs(self): t = typevar('t') u = typevar('u') class C(Generic[t, u]): pass self.assertIs(C[int, str], C) self.assertIsInstance(C(), C) self.assertIsInstance(C[int, str](), C)
def test_generic_protocol(self): t = typevar(u't') class P(Protocol[t]): x = 1 class A(object): x = 2 self.assertIsInstance(A(), P)
def test_generic_protocol(self): t = typevar('t') class P(Protocol[t]): x = 1 class A: x = 2 self.assertIsInstance(A(), P)
def test_simple_generic_class(self): t = typevar('t') class C(Generic[t]): pass self.assertIs(C[int], C) self.assertIsInstance(C(), C) self.assertIsInstance(C[int](), C)
def test_abstract_generic_class(self): t = typevar(u't') class C(AbstractGeneric[t]): pass class D(object): pass self.assertIs(C[int], C) self.assertNotIsInstance(D(), C) C.register(D) self.assertIsInstance(D(), C)
def test_typevar_in_overload(self): t = typevar('t') @overload def f(x:t, y:str): return 1 @overload def f(x, y): return 2 self.assertEqual(f((), 'x'), 1) self.assertEqual(f((), 1.1), 2)
def test_abstract_generic_class(self): t = typevar('t') class C(AbstractGeneric[t]): pass class D: pass self.assertIs(C[int], C) self.assertNotIsInstance(D(), C) C.register(D) self.assertIsInstance(D(), C)
def test_typevar_in_overload(self): t = typevar(u't') @overload def f(x, y): return 1 @overload def f(x, y): return 2 self.assertEqual(f((), u'x'), 1) self.assertEqual(f((), 1.1), 2)
def test_construct_class_with_abstract_method(self): t = typevar('t') class A(AbstractGeneric[t]): @abstractmethod def f(self): pass class B(A): def f(self): pass with self.assertRaises(TypeError): A() B()
def test_construct_class_with_abstract_method(self): t = typevar(u't') class A(AbstractGeneric[t]): @abstractmethod def f(self): pass class B(A): def f(self): pass with self.assertRaises(TypeError): A() B()
def test_typevar_values(self): t = typevar('t', values=(int, str)) self.assertEqual(t.name, 't') self.assertEqual(t.values, (int, str))
from typing import typevar, Any _FT = typevar("_FT") def register(func: _FT, *args: Any, **kargs: Any) -> _FT: pass
"""Stubs for builtins""" from typing import ( Undefined, typevar, AbstractGeneric, Iterator, Iterable, overload, Sequence, Mapping, Tuple, List, Any, Dict, Function, Generic, Set, AbstractSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, SupportsRound, IO, builtinclass, ducktype, Union ) from abc import abstractmethod, ABCMeta # Note that names imported above are not automatically made visible via the # implicit builtins import. T = typevar('T') KT = typevar('KT') VT = typevar('VT') S = typevar('S') T1 = typevar('T1') T2 = typevar('T2') T3 = typevar('T3') T4 = typevar('T4') staticmethod = object() # Only valid as a decorator. classmethod = object() # Only valid as a decorator. property = object() _byte_types = Union[bytes, bytearray] @builtinclass
"""Generic abstract syntax tree node visitor""" from typing import typevar, Generic import mypy.nodes T = typevar('T') class NodeVisitor(Generic[T]): """Empty base class for parse tree node visitors. The T type argument specifies the return type of the visit methods. As all methods defined here return None by default, subclasses do not always need to override all the methods. TODO make the default return value explicit """ # Module structure def visit_mypy_file(self, o: 'mypy.nodes.MypyFile') -> T: pass def visit_import(self, o: 'mypy.nodes.Import') -> T: pass def visit_import_from(self, o: 'mypy.nodes.ImportFrom') -> T: pass def visit_import_all(self, o: 'mypy.nodes.ImportAll') -> T: pass
def test_typevar(self): t = typevar(u't') self.assertEqual(t.name, u't')
# Stubs for unittest # Based on http://docs.python.org/3.0/library/unittest.html # NOTE: These stubs are based on the 3.0 version API, since later versions # would require featurs not supported currently by mypy. # Only a subset of functionality is included. from typing import ( Any, Function, Iterable, Undefined, Tuple, List, TextIO, Sequence, overload, typevar, Pattern ) from abc import abstractmethod, ABCMeta _T = typevar('_T') _FT = typevar('_FT') class Testable(metaclass=ABCMeta): @abstractmethod def run(self, result: 'TestResult') -> None: pass @abstractmethod def debug(self) -> None: pass @abstractmethod def countTestCases(self) -> int: pass # TODO ABC for test runners? class TestResult: errors = Undefined(List[Tuple[Testable, str]]) failures = Undefined(List[Tuple[Testable, str]])
# Stubs for itertools # Based on http://docs.python.org/3.2/library/itertools.html from typing import (Iterator, typevar, Iterable, overload, Any, Function, Tuple, Union, Sequence) _T = typevar('_T') _S = typevar('_S') def count(start: int = 0, step: int = 1) -> Iterator[int]: pass # more general types? def cycle(iterable: Iterable[_T]) -> Iterator[_T]: pass @overload def repeat(object: _T) -> Iterator[_T]: pass @overload def repeat(object: _T, times: int) -> Iterator[_T]: pass def accumulate(iterable: Iterable[_T]) -> Iterator[_T]: pass
#!/usr/bin/env python3 import unittest import random import time import pickle import warnings from math import log, exp, pi, fsum, sin from test import support from typing import Undefined, Any, Dict, List, Function, Generic, typevar RT = typevar('RT', values=(random.Random, random.SystemRandom)) class TestBasicOps(unittest.TestCase, Generic[RT]): # Superclass with tests common to all generators. # Subclasses must arrange for self.gen to retrieve the Random instance # to be tested. gen = Undefined(RT) # Either Random or SystemRandom def randomlist(self, n: int) -> List[float]: """Helper function to make a list of random numbers""" return [self.gen.random() for i in range(n)] def test_autoseed(self) -> None: self.gen.seed() state1 = self.gen.getstate() time.sleep(0.1) self.gen.seed() # diffent seeds at different times
# Stubs for builtins (Python 2.7) from typing import ( Undefined, typevar, AbstractGeneric, Iterator, Iterable, overload, Sequence, Mapping, Tuple, List, Any, Dict, Function, Generic, Set, AbstractSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, SupportsRound, IO, BinaryIO, builtinclass, ducktype, Union, AnyStr ) from abc import abstractmethod, ABCMeta _T = typevar('_T') _KT = typevar('_KT') _VT = typevar('_VT') _S = typevar('_S') _T1 = typevar('_T1') _T2 = typevar('_T2') _T3 = typevar('_T3') _T4 = typevar('_T4') staticmethod = object() # Only valid as a decorator. classmethod = object() # Only valid as a decorator. property = object() @builtinclass class object: __doc__ = '' __class__ = Undefined # type: type def __init__(self) -> None: pass def __eq__(self, o: object) -> bool: pass def __ne__(self, o: object) -> bool: pass
"""Stubs for builtins""" from typing import (Undefined, typevar, AbstractGeneric, Iterator, Iterable, overload, Sequence, Mapping, Tuple, List, Any, Dict, Function, Generic, Set, AbstractSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, SupportsRound, IO, builtinclass, ducktype, Union) from abc import abstractmethod, ABCMeta # Note that names imported above are not automatically made visible via the # implicit builtins import. T = typevar('T') KT = typevar('KT') VT = typevar('VT') S = typevar('S') T1 = typevar('T1') T2 = typevar('T2') T3 = typevar('T3') T4 = typevar('T4') staticmethod = object() # Only valid as a decorator. classmethod = object() # Only valid as a decorator. property = object() _byte_types = Union[bytes, bytearray] @builtinclass class object: __doc__ = ''
from typing import typevar, Any FT = typevar('FT') def register(func: FT, *args: Any, **kargs: Any) -> FT: pass
# These builtins stubs are used implicitly in parse-tree to icode generation # test cases (testicodegen.py and test/data/icode-basic.test). from typing import typevar, Generic t = typevar('t') class object: def __init__(self) -> None: pass class type: pass class str: pass # Primitive types are special in generated code. class int: def __add__(self, n: int) -> int: pass def __sub__(self, n: int) -> int: pass def __mul__(self, n: int) -> int: pass def __neg__(self) -> int: pass def __eq__(self, n: int) -> bool: pass def __ne__(self, n: int) -> bool: pass def __lt__(self, n: int) -> bool: pass def __gt__(self, n: int) -> bool: pass def __le__(self, n: int) -> bool: pass def __ge__(self, n: int) -> bool: pass class float: pass class bool: pass class list(Generic[t]): pass
# Stubs for unittest # Based on http://docs.python.org/3.0/library/unittest.html # NOTE: These stubs are based on the 3.0 version API, since later versions # would require featurs not supported currently by mypy. # Only a subset of functionality is included. from typing import ( Any, Function, Iterable, Undefined, Tuple, List, TextIO, Sequence, overload, typevar, Pattern ) from abc import abstractmethod, ABCMeta T = typevar('T') FT = typevar('FT') class Testable(metaclass=ABCMeta): @abstractmethod def run(self, result: 'TestResult') -> None: pass @abstractmethod def debug(self) -> None: pass @abstractmethod def countTestCases(self) -> int: pass # TODO ABC for test runners? class TestResult: errors = Undefined(List[Tuple[Testable, str]]) failures = Undefined(List[Tuple[Testable, str]])
# Stubs for builtins (Python 2.7) from typing import (Undefined, typevar, AbstractGeneric, Iterator, Iterable, overload, Sequence, Mapping, Tuple, List, Any, Dict, Function, Generic, Set, AbstractSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, SupportsRound, IO, BinaryIO, builtinclass, ducktype, Union, AnyStr) from abc import abstractmethod, ABCMeta _T = typevar('_T') _KT = typevar('_KT') _VT = typevar('_VT') _S = typevar('_S') _T1 = typevar('_T1') _T2 = typevar('_T2') _T3 = typevar('_T3') _T4 = typevar('_T4') staticmethod = object() # Only valid as a decorator. classmethod = object() # Only valid as a decorator. property = object() @builtinclass class object: __doc__ = '' __class__ = Undefined # type: type def __init__(self) -> None: pass
# These builtins stubs are used implicitly in parse-tree to icode generation # test cases (testicodegen.py and test/data/icode-basic.test). from typing import typevar, Generic t = typevar('t') class object: def __init__(self) -> None: pass class type: pass class str: pass # Primitive types are special in generated code. class int: def __add__(self, n: int) -> int: pass def __sub__(self, n: int) -> int: pass
# Stubs for collections # Based on http://docs.python.org/3.2/library/collections.html # TODO UserDict # TODO UserList # TODO UserString # TODO more abstract base classes (interfaces in mypy) from typing import (typevar, Iterable, AbstractGeneric, Iterator, Dict, Generic, overload, Mapping, List, Tuple, Undefined, Function, Set, Sequence, Sized) _T = typevar('_T') _KT = typevar('_KT') _VT = typevar('_VT') # namedtuple is special-cased in the type checker; the initializer is ignored. namedtuple = object() class deque(Sized, Iterable[_T], AbstractGeneric[_T]): # TODO int with None default maxlen = 0 # TODO readonly def __init__(self, iterable: Iterable[_T] = None, maxlen: int = None) -> None: pass def append(self, x: _T) -> None:
from asyncio.events import AbstractEventLoop from asyncio.futures import Future # __all__ = ['iscoroutinefunction', 'iscoroutine', # 'as_completed', 'async', # 'gather', 'shield', # ] __all__ = [ 'coroutine', 'Task', 'sleep', 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED', 'wait', 'wait_for' ] FIRST_EXCEPTION = 'FIRST_EXCEPTION' FIRST_COMPLETED = 'FIRST_COMPLETED' ALL_COMPLETED = 'ALL_COMPLETED' _T = typevar('_T') def coroutine(f: _T) -> _T: pass # Here comes and go a function def sleep(delay: float, result: _T = None, loop: AbstractEventLoop = None) -> Future[_T]: pass def wait( fs: List[Task[_T]], *,
# Stubs for builtins from typing import ( Undefined, typevar, AbstractGeneric, Iterator, Iterable, overload, Sequence, Mapping, Tuple, List, Any, Dict, Function, Generic, Set, AbstractSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, SupportsRound, IO, builtinclass, ducktype, Union ) from abc import abstractmethod, ABCMeta # Note that names imported above are not automatically made visible via the # implicit builtins import. _T = typevar('_T') _KT = typevar('_KT') _VT = typevar('_VT') _S = typevar('_S') _T1 = typevar('_T1') _T2 = typevar('_T2') _T3 = typevar('_T3') _T4 = typevar('_T4') staticmethod = object() # Only valid as a decorator. classmethod = object() # Only valid as a decorator. property = object() _byte_types = Union[bytes, bytearray] @builtinclass class object: __doc__ = ''
"""Stubs for builtins""" from typing import ( Undefined, typevar, AbstractGeneric, Iterator, Iterable, overload, Sequence, Mapping, Tuple, List, Any, Dict, Function, Generic, Set, AbstractSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, SupportsRound, TextIO ) from abc import abstractmethod, ABCMeta T = typevar('T') KT = typevar('KT') VT = typevar('VT') S = typevar('S') T1 = typevar('T1') T2 = typevar('T2') T3 = typevar('T3') T4 = typevar('T4') staticmethod = object() # Only valid as a decorator. property = object() class object: __doc__ = '' __class__ = Undefined # type: type def __init__(self) -> None: pass def __eq__(self, o: object) -> bool: pass
def test_typevar(self): t = typevar('t') self.assertEqual(t.name, 't') self.assertIsNone(t.values)
# Stubs for collections # Based on http://docs.python.org/3.2/library/collections.html # TODO namedtuple (requires language changes) # TODO UserDict # TODO UserList # TODO UserString # TODO more abstract base classes (interfaces in mypy) from typing import (typevar, Iterable, AbstractGeneric, Iterator, Dict, Generic, overload, Mapping, List, Tuple, Undefined, Function, Set, Sequence, Sized) T = typevar('T') KT = typevar('KT') VT = typevar('VT') class deque(Sized, Iterable[T], AbstractGeneric[T]): # TODO int with None default maxlen = 0 # TODO readonly def __init__(self, iterable: Iterable[T] = None, maxlen: int = None) -> None: pass def append(self, x: T) -> None: pass
# Stubs for weakref # NOTE: These are incomplete! from typing import ( typevar, Generic, Any, Function, overload, Mapping, Iterator, Dict, Tuple, Iterable ) _T = typevar('_T') _KT = typevar('_KT') _VT = typevar('_VT') class ReferenceType(Generic[_T]): # TODO members pass def ref(o: _T, callback: Function[[ReferenceType[_T]], Any] = None) -> ReferenceType[_T]: pass # TODO callback def proxy(object: _T) -> _T: pass class WeakValueDictionary(Generic[_KT, _VT]): # TODO tuple iterable argument? @overload def __init__(self) -> None: pass @overload def __init__(self, map: Mapping[_KT, _VT]) -> None: pass def __len__(self) -> int: pass
# Stubs for unittest # Based on http://docs.python.org/3.0/library/unittest.html # NOTE: These stubs are based on the 3.0 version API, since later versions # would require featurs not supported currently by mypy. # Only a subset of functionality is included. from typing import (Any, Function, Iterable, Undefined, Tuple, List, TextIO, Sequence, overload, typevar, Pattern) from abc import abstractmethod, ABCMeta _T = typevar('_T') _FT = typevar('_FT') class Testable(metaclass=ABCMeta): @abstractmethod def run(self, result: 'TestResult') -> None: pass @abstractmethod def debug(self) -> None: pass @abstractmethod def countTestCases(self) -> int: pass
# Stubs for itertools # Based on http://docs.python.org/3.2/library/itertools.html from typing import Iterator, typevar, Iterable, overload, Any, Function, Tuple T = typevar('T') S = typevar('S') def count(start: int = 0, step: int = 1) -> Iterator[int]: pass # more general types? def cycle(iterable: Iterable[T]) -> Iterator[T]: pass @overload def repeat(object: T) -> Iterator[T]: pass @overload def repeat(object: T, times: int) -> Iterator[T]: pass def accumulate(iterable: Iterable[T]) -> Iterator[T]: pass
#!/usr/bin/env python3 import unittest import random import time import pickle import warnings from math import log, exp, pi, fsum, sin from test import support from typing import Undefined, Any, Dict, List, Function, Generic, typevar RT = typevar('RT', values=(random.Random, random.SystemRandom)) class TestBasicOps(unittest.TestCase, Generic[RT]): # Superclass with tests common to all generators. # Subclasses must arrange for self.gen to retrieve the Random instance # to be tested. gen = Undefined(RT) # Either Random or SystemRandom def randomlist(self, n: int) -> List[float]: """Helper function to make a list of random numbers""" return [self.gen.random() for i in range(n)] def test_autoseed(self) -> None: self.gen.seed() state1 = self.gen.getstate() time.sleep(0.1) self.gen.seed() # diffent seeds at different times state2 = self.gen.getstate()
# Builtins stub used in dictionary-related test cases. from typing import typevar, Generic, Iterable, Iterator T = typevar('T') S = typevar('S') class object: def __init__(self) -> None: pass class type: pass class dict(Generic[T, S]): pass class int: pass # for convenience class str: pass # for keyword argument key type class list(Iterable[T], Generic[T]): # needed by some test cases def __iter__(self) -> Iterator[T]: pass def __mul__(self, x: int) -> list[T]: pass
# Stubs for collections # Based on http://docs.python.org/3.2/library/collections.html # TODO namedtuple (requires language changes) # TODO UserDict # TODO UserList # TODO UserString # TODO more abstract base classes (interfaces in mypy) from typing import ( typevar, Iterable, AbstractGeneric, Iterator, Dict, Generic, overload, Mapping, List, Tuple, Undefined, Function, Set, Sequence, Sized ) T = typevar('T') KT = typevar('KT') VT = typevar('VT') class deque(Sized, Iterable[T], AbstractGeneric[T]): # TODO int with None default maxlen = 0 # TODO readonly def __init__(self, iterable: Iterable[T] = None, maxlen: int = None) -> None: pass def append(self, x: T) -> None: pass def appendleft(self, x: T) -> None: pass def clear(self) -> None: pass def count(self, x: T) -> int: pass def extend(self, iterable: Iterable[T]) -> None: pass def extendleft(self, iterable: Iterable[T]) -> None: pass
# Stubs for itertools # Based on http://docs.python.org/3.2/library/itertools.html from typing import Iterator, typevar, Iterable, overload, Any, Function, Tuple, Union, Sequence _T = typevar("_T") _S = typevar("_S") def count(start: int = 0, step: int = 1) -> Iterator[int]: pass # more general types? def cycle(iterable: Iterable[_T]) -> Iterator[_T]: pass @overload def repeat(object: _T) -> Iterator[_T]: pass @overload def repeat(object: _T, times: int) -> Iterator[_T]: pass def accumulate(iterable: Iterable[_T]) -> Iterator[_T]: pass
# Stubs for unittest # Based on http://docs.python.org/3.0/library/unittest.html # NOTE: These stubs are based on the 3.0 version API, since later versions # would require featurs not supported currently by mypy. # Only a subset of functionality is included. from typing import ( Any, Function, Iterable, Undefined, Tuple, List, TextIO, typevar ) from abc import abstractmethod, ABCMeta FT = typevar('FT') class Testable(metaclass=ABCMeta): @abstractmethod def run(self, result: 'TestResult') -> None: pass @abstractmethod def debug(self) -> None: pass @abstractmethod def countTestCases(self) -> int: pass # TODO ABC for test runners? class TestResult: errors = Undefined(List[Tuple[Testable, str]]) failures = Undefined(List[Tuple[Testable, str]]) testsRun = 0 shouldStop = False
from abc import ABCMeta, abstractmethod from asyncio.futures import Future import socket, subprocess # __all__ = ['AbstractEventLoopPolicy', # 'AbstractEventLoop', 'AbstractServer', # 'Handle', 'TimerHandle', # 'get_event_loop_policy', 'set_event_loop_policy', # 'get_event_loop', 'set_event_loop', 'new_event_loop', # 'get_child_watcher', 'set_child_watcher', # ] __all__ = ['AbstractEventLoop', 'Handle', 'get_event_loop'] _T = typevar('_T') class Handle: __slots__ = [] # type: List[str] _cancelled = False _args = [] # type: List[Any] def __init__(self, callback: Function[[],Any], args: List[Any], loop: AbstractEventLoop) -> None: pass def __repr__(self) -> str: pass def cancel(self) -> None: pass def _run(self) -> None: pass class AbstractEventLoop(metaclass=ABCMeta): @abstractmethod def run_forever(self) -> None: pass
from mypy.visitor import NodeVisitor from mypy.util import dump_tagged, short_type class Context(metaclass=ABCMeta): """Base type for objects that are valid as error message locations.""" # @abstractmethod def get_line(self) -> int: pass import mypy.types T = typevar("T") # Variable kind constants # TODO rename to use more descriptive names LDEF = 0 # type: int GDEF = 1 # type: int MDEF = 2 # type: int MODULE_REF = 3 # type: int # Type variable declared using typevar(...) has kind UNBOUND_TVAR. It's not # valid as a type. A type variable is valid as a type (kind TVAR) within # (1) a generic class that uses the type variable as a type argument or # (2) a generic function that refers to the type variable in its signature. UNBOUND_TVAR = 4 # type: 'int' TVAR = 5 # type: int
from typing import typevar, Any _FT = typevar('_FT') def register(func: _FT, *args: Any, **kargs: Any) -> _FT: pass
"""Utility functions.""" from typing import typevar, List, Any T = typevar('T') def short_type(obj: object) -> str: """Return the last component of the type name of an object. If obj is None, return 'nil'. For example, if obj is 1, return 'int'. """ if obj is None: return 'nil' t = str(type(obj)) return t.split('.')[-1].rstrip("'>") def indent(s: str, n: int) -> str: """Indent all the lines in s (separated by Newlines) by n spaces.""" s = ' ' * n + s s = s.replace('\n', '\n' + ' ' * n) return s def array_repr(a: List[T]) -> List[str]: """Return the items of an array converted to strings using Repr.""" aa = [] # type: List[str] for x in a: aa.append(repr(x)) return aa
__author__ = 'Administrator' from typing import Iterator, typevar, Generic, Function, List T = typevar('T') def example_typed(x : Iterator[int]) -> Iterator[str]: for i in x: yield str(i) def example_generic(x : Iterator[T]) -> Iterator[T]: for i in x: yield i a = typevar('a') b = typevar('b') class Functor(Generic[a]): def __init__(self, xs : List[a]) -> None: self._storage = xs def iter(self) -> Iterator[a]: return iter(self._storage) def fmap(f : Function[[a], b], xs : Functor[a]) -> Functor[b]: return Functor([f(x) for x in xs.iter()]) class Monad(Generic[a]): def __init__(self, val : a) -> None: