Issue #23973: Update typing.py from GitHub repo. (Merge from 3.5.)

This commit is contained in:
Guido van Rossum 2015-08-05 12:13:11 +02:00
commit a9d77fad34
3 changed files with 74 additions and 11 deletions

View file

@ -459,6 +459,14 @@ class CallableTests(TestCase):
ctv = Callable[..., str] ctv = Callable[..., str]
self.assertEqual(repr(ctv), 'typing.Callable[..., str]') self.assertEqual(repr(ctv), 'typing.Callable[..., str]')
def test_callable_with_ellipsis(self):
def foo(a: Callable[..., T]):
pass
self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': Callable[..., T]})
XK = TypeVar('XK', str, bytes) XK = TypeVar('XK', str, bytes)
XV = TypeVar('XV') XV = TypeVar('XV')
@ -555,6 +563,14 @@ class GenericTests(TestCase):
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
Y[str, bytes] Y[str, bytes]
def test_init(self):
T = TypeVar('T')
S = TypeVar('S')
with self.assertRaises(TypeError):
Generic[T, T]
with self.assertRaises(TypeError):
Generic[T, S, T]
def test_repr(self): def test_repr(self):
self.assertEqual(repr(SimpleMapping), self.assertEqual(repr(SimpleMapping),
__name__ + '.' + 'SimpleMapping[~XK, ~XV]') __name__ + '.' + 'SimpleMapping[~XK, ~XV]')
@ -801,6 +817,14 @@ class ForwardRefTests(TestCase):
self.assertEqual(get_type_hints(foo, globals(), locals()), self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': Callable[[T], T]}) {'a': Callable[[T], T]})
def test_callable_with_ellipsis_forward(self):
def foo(a: 'Callable[..., T]'):
pass
self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': Callable[..., T]})
def test_syntax_error(self): def test_syntax_error(self):
with self.assertRaises(SyntaxError): with self.assertRaises(SyntaxError):

View file

@ -128,6 +128,8 @@ class TypingMeta(type):
class Final: class Final:
"""Mix-in class to prevent instantiation.""" """Mix-in class to prevent instantiation."""
__slots__ = ()
def __new__(self, *args, **kwds): def __new__(self, *args, **kwds):
raise TypeError("Cannot instantiate %r" % self.__class__) raise TypeError("Cannot instantiate %r" % self.__class__)
@ -204,6 +206,8 @@ class _TypeAlias:
False. False.
""" """
__slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
def __new__(cls, *args, **kwds): def __new__(cls, *args, **kwds):
"""Constructor. """Constructor.
@ -341,6 +345,8 @@ class Any(Final, metaclass=AnyMeta, _root=True):
- As a special case, Any and object are subclasses of each other. - As a special case, Any and object are subclasses of each other.
""" """
__slots__ = ()
class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True): class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
"""Type variable. """Type variable.
@ -635,6 +641,8 @@ class Optional(Final, metaclass=OptionalMeta, _root=True):
Optional[X] is equivalent to Union[X, type(None)]. Optional[X] is equivalent to Union[X, type(None)].
""" """
__slots__ = ()
class TupleMeta(TypingMeta): class TupleMeta(TypingMeta):
"""Metaclass for Tuple.""" """Metaclass for Tuple."""
@ -734,6 +742,8 @@ class Tuple(Final, metaclass=TupleMeta, _root=True):
To specify a variable-length tuple of homogeneous type, use Sequence[T]. To specify a variable-length tuple of homogeneous type, use Sequence[T].
""" """
__slots__ = ()
class CallableMeta(TypingMeta): class CallableMeta(TypingMeta):
"""Metaclass for Callable.""" """Metaclass for Callable."""
@ -767,7 +777,10 @@ class CallableMeta(TypingMeta):
def _eval_type(self, globalns, localns): def _eval_type(self, globalns, localns):
if self.__args__ is None and self.__result__ is None: if self.__args__ is None and self.__result__ is None:
return self return self
args = [_eval_type(t, globalns, localns) for t in self.__args__] if self.__args__ is Ellipsis:
args = self.__args__
else:
args = [_eval_type(t, globalns, localns) for t in self.__args__]
result = _eval_type(self.__result__, globalns, localns) result = _eval_type(self.__result__, globalns, localns)
if args == self.__args__ and result == self.__result__: if args == self.__args__ and result == self.__result__:
return self return self
@ -837,6 +850,8 @@ class Callable(Final, metaclass=CallableMeta, _root=True):
such function types are rarely used as callback types. such function types are rarely used as callback types.
""" """
__slots__ = ()
def _gorg(a): def _gorg(a):
"""Return the farthest origin of a generic class.""" """Return the farthest origin of a generic class."""
@ -947,6 +962,8 @@ class GenericMeta(TypingMeta, abc.ABCMeta):
if not isinstance(p, TypeVar): if not isinstance(p, TypeVar):
raise TypeError("Initial parameters must be " raise TypeError("Initial parameters must be "
"type variables; got %s" % p) "type variables; got %s" % p)
if len(set(params)) != len(params):
raise TypeError("All type variables in Generic[...] must be distinct.")
else: else:
if len(params) != len(self.__parameters__): if len(params) != len(self.__parameters__):
raise TypeError("Cannot change parameter count from %d to %d" % raise TypeError("Cannot change parameter count from %d to %d" %
@ -1039,6 +1056,8 @@ class Generic(metaclass=GenericMeta):
# Same body as above. # Same body as above.
""" """
__slots__ = ()
def __new__(cls, *args, **kwds): def __new__(cls, *args, **kwds):
next_in_mro = object next_in_mro = object
# Look for the last occurrence of Generic or Generic[...]. # Look for the last occurrence of Generic or Generic[...].
@ -1205,6 +1224,7 @@ class _ProtocolMeta(GenericMeta):
attr != '__abstractmethods__' and attr != '__abstractmethods__' and
attr != '_is_protocol' and attr != '_is_protocol' and
attr != '__dict__' and attr != '__dict__' and
attr != '__slots__' and
attr != '_get_protocol_attrs' and attr != '_get_protocol_attrs' and
attr != '__parameters__' and attr != '__parameters__' and
attr != '__origin__' and attr != '__origin__' and
@ -1222,6 +1242,8 @@ class _Protocol(metaclass=_ProtocolMeta):
such as Hashable). such as Hashable).
""" """
__slots__ = ()
_is_protocol = True _is_protocol = True
@ -1232,14 +1254,15 @@ Hashable = collections_abc.Hashable # Not generic.
class Iterable(Generic[T_co], extra=collections_abc.Iterable): class Iterable(Generic[T_co], extra=collections_abc.Iterable):
pass __slots__ = ()
class Iterator(Iterable[T_co], extra=collections_abc.Iterator): class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
pass __slots__ = ()
class SupportsInt(_Protocol): class SupportsInt(_Protocol):
__slots__ = ()
@abstractmethod @abstractmethod
def __int__(self) -> int: def __int__(self) -> int:
@ -1247,6 +1270,7 @@ class SupportsInt(_Protocol):
class SupportsFloat(_Protocol): class SupportsFloat(_Protocol):
__slots__ = ()
@abstractmethod @abstractmethod
def __float__(self) -> float: def __float__(self) -> float:
@ -1254,6 +1278,7 @@ class SupportsFloat(_Protocol):
class SupportsComplex(_Protocol): class SupportsComplex(_Protocol):
__slots__ = ()
@abstractmethod @abstractmethod
def __complex__(self) -> complex: def __complex__(self) -> complex:
@ -1261,30 +1286,34 @@ class SupportsComplex(_Protocol):
class SupportsBytes(_Protocol): class SupportsBytes(_Protocol):
__slots__ = ()
@abstractmethod @abstractmethod
def __bytes__(self) -> bytes: def __bytes__(self) -> bytes:
pass pass
class SupportsAbs(_Protocol[T]): class SupportsAbs(_Protocol[T_co]):
__slots__ = ()
@abstractmethod @abstractmethod
def __abs__(self) -> T: def __abs__(self) -> T_co:
pass pass
class SupportsRound(_Protocol[T]): class SupportsRound(_Protocol[T_co]):
__slots__ = ()
@abstractmethod @abstractmethod
def __round__(self, ndigits: int = 0) -> T: def __round__(self, ndigits: int = 0) -> T_co:
pass pass
class Reversible(_Protocol[T]): class Reversible(_Protocol[T_co]):
__slots__ = ()
@abstractmethod @abstractmethod
def __reversed__(self) -> 'Iterator[T]': def __reversed__(self) -> 'Iterator[T_co]':
pass pass
@ -1292,7 +1321,7 @@ Sized = collections_abc.Sized # Not generic.
class Container(Generic[T_co], extra=collections_abc.Container): class Container(Generic[T_co], extra=collections_abc.Container):
pass __slots__ = ()
# Callable was defined earlier. # Callable was defined earlier.
@ -1308,7 +1337,7 @@ class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
# NOTE: Only the value type is covariant. # NOTE: Only the value type is covariant.
class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co], class Mapping(Sized, Iterable[KT], Container[KT], Generic[VT_co],
extra=collections_abc.Mapping): extra=collections_abc.Mapping):
pass pass
@ -1366,6 +1395,7 @@ class _FrozenSetMeta(GenericMeta):
class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta): class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta):
__slots__ = ()
def __new__(cls, *args, **kwds): def __new__(cls, *args, **kwds):
if _geqv(cls, FrozenSet): if _geqv(cls, FrozenSet):
@ -1413,6 +1443,7 @@ else:
class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co], class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
extra=_G_base): extra=_G_base):
__slots__ = ()
def __new__(cls, *args, **kwds): def __new__(cls, *args, **kwds):
if _geqv(cls, Generator): if _geqv(cls, Generator):
@ -1456,6 +1487,8 @@ class IO(Generic[AnyStr]):
way to track the other distinctions in the type system. way to track the other distinctions in the type system.
""" """
__slots__ = ()
@abstractproperty @abstractproperty
def mode(self) -> str: def mode(self) -> str:
pass pass
@ -1540,6 +1573,8 @@ class IO(Generic[AnyStr]):
class BinaryIO(IO[bytes]): class BinaryIO(IO[bytes]):
"""Typed version of the return of open() in binary mode.""" """Typed version of the return of open() in binary mode."""
__slots__ = ()
@abstractmethod @abstractmethod
def write(self, s: Union[bytes, bytearray]) -> int: def write(self, s: Union[bytes, bytearray]) -> int:
pass pass
@ -1552,6 +1587,8 @@ class BinaryIO(IO[bytes]):
class TextIO(IO[str]): class TextIO(IO[str]):
"""Typed version of the return of open() in text mode.""" """Typed version of the return of open() in text mode."""
__slots__ = ()
@abstractproperty @abstractproperty
def buffer(self) -> BinaryIO: def buffer(self) -> BinaryIO:
pass pass

View file

@ -13,6 +13,8 @@ Core and Builtins
Library Library
------- -------
- Issue #23973: Update typing.py from GitHub repo.
- Issue #23888: Handle fractional time in cookie expiry. Patch by ssh. - Issue #23888: Handle fractional time in cookie expiry. Patch by ssh.
- Issue #23652: Make it possible to compile the select module against the - Issue #23652: Make it possible to compile the select module against the