mypy_extensions.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. """Defines experimental extensions to the standard "typing" module that are
  2. supported by the mypy typechecker.
  3. Example usage:
  4. from mypy_extensions import TypedDict
  5. """
  6. from typing import Any
  7. import sys
  8. # _type_check is NOT a part of public typing API, it is used here only to mimic
  9. # the (convenient) behavior of types provided by typing module.
  10. from typing import _type_check # type: ignore
  11. def _check_fails(cls, other):
  12. try:
  13. if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools', 'typing']:
  14. # Typed dicts are only for static structural subtyping.
  15. raise TypeError('TypedDict does not support instance and class checks')
  16. except (AttributeError, ValueError):
  17. pass
  18. return False
  19. def _dict_new(cls, *args, **kwargs):
  20. return dict(*args, **kwargs)
  21. def _typeddict_new(cls, _typename, _fields=None, **kwargs):
  22. total = kwargs.pop('total', True)
  23. if _fields is None:
  24. _fields = kwargs
  25. elif kwargs:
  26. raise TypeError("TypedDict takes either a dict or keyword arguments,"
  27. " but not both")
  28. ns = {'__annotations__': dict(_fields), '__total__': total}
  29. try:
  30. # Setting correct module is necessary to make typed dict classes pickleable.
  31. ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
  32. except (AttributeError, ValueError):
  33. pass
  34. return _TypedDictMeta(_typename, (), ns)
  35. class _TypedDictMeta(type):
  36. def __new__(cls, name, bases, ns, total=True):
  37. # Create new typed dict class object.
  38. # This method is called directly when TypedDict is subclassed,
  39. # or via _typeddict_new when TypedDict is instantiated. This way
  40. # TypedDict supports all three syntaxes described in its docstring.
  41. # Subclasses and instances of TypedDict return actual dictionaries
  42. # via _dict_new.
  43. ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
  44. tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
  45. anns = ns.get('__annotations__', {})
  46. msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
  47. anns = {n: _type_check(tp, msg) for n, tp in anns.items()}
  48. for base in bases:
  49. anns.update(base.__dict__.get('__annotations__', {}))
  50. tp_dict.__annotations__ = anns
  51. if not hasattr(tp_dict, '__total__'):
  52. tp_dict.__total__ = total
  53. return tp_dict
  54. __instancecheck__ = __subclasscheck__ = _check_fails
  55. TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
  56. TypedDict.__module__ = __name__
  57. TypedDict.__doc__ = \
  58. """A simple typed name space. At runtime it is equivalent to a plain dict.
  59. TypedDict creates a dictionary type that expects all of its
  60. instances to have a certain set of keys, with each key
  61. associated with a value of a consistent type. This expectation
  62. is not checked at runtime but is only enforced by typecheckers.
  63. Usage::
  64. Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
  65. a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
  66. b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
  67. assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
  68. The type info could be accessed via Point2D.__annotations__. TypedDict
  69. supports two additional equivalent forms::
  70. Point2D = TypedDict('Point2D', x=int, y=int, label=str)
  71. class Point2D(TypedDict):
  72. x: int
  73. y: int
  74. label: str
  75. The latter syntax is only supported in Python 3.6+, while two other
  76. syntax forms work for 3.2+
  77. """
  78. # Argument constructors for making more-detailed Callables. These all just
  79. # return their type argument, to make them complete noops in terms of the
  80. # `typing` module.
  81. def Arg(type=Any, name=None):
  82. """A normal positional argument"""
  83. return type
  84. def DefaultArg(type=Any, name=None):
  85. """A positional argument with a default value"""
  86. return type
  87. def NamedArg(type=Any, name=None):
  88. """A keyword-only argument"""
  89. return type
  90. def DefaultNamedArg(type=Any, name=None):
  91. """A keyword-only argument with a default value"""
  92. return type
  93. def VarArg(type=Any):
  94. """A *args-style variadic positional argument"""
  95. return type
  96. def KwArg(type=Any):
  97. """A **kwargs-style variadic keyword argument"""
  98. return type
  99. # Return type that indicates a function does not return
  100. class NoReturn: pass
  101. def trait(cls):
  102. return cls
  103. def mypyc_attr(*attrs, **kwattrs):
  104. return lambda x: x
  105. # TODO: We may want to try to properly apply this to any type
  106. # variables left over...
  107. class _FlexibleAliasClsApplied:
  108. def __init__(self, val):
  109. self.val = val
  110. def __getitem__(self, args):
  111. return self.val
  112. class _FlexibleAliasCls:
  113. def __getitem__(self, args):
  114. return _FlexibleAliasClsApplied(args[-1])
  115. FlexibleAlias = _FlexibleAliasCls()
  116. class _NativeIntMeta(type):
  117. def __instancecheck__(cls, inst):
  118. return isinstance(inst, int)
  119. _sentinel = object()
  120. class i64(metaclass=_NativeIntMeta):
  121. def __new__(cls, x=0, base=_sentinel):
  122. if base is not _sentinel:
  123. return int(x, base)
  124. return int(x)
  125. class i32(metaclass=_NativeIntMeta):
  126. def __new__(cls, x=0, base=_sentinel):
  127. if base is not _sentinel:
  128. return int(x, base)
  129. return int(x)
  130. class i16(metaclass=_NativeIntMeta):
  131. def __new__(cls, x=0, base=_sentinel):
  132. if base is not _sentinel:
  133. return int(x, base)
  134. return int(x)
  135. class u8(metaclass=_NativeIntMeta):
  136. def __new__(cls, x=0, base=_sentinel):
  137. if base is not _sentinel:
  138. return int(x, base)
  139. return int(x)
  140. for _int_type in i64, i32, i16, u8:
  141. _int_type.__doc__ = \
  142. """A native fixed-width integer type when used with mypyc.
  143. In code not compiled with mypyc, behaves like the 'int' type in these
  144. runtime contexts:
  145. * {name}(x[, base=n]) converts a number or string to 'int'
  146. * isinstance(x, {name}) is the same as isinstance(x, int)
  147. """.format(name=_int_type.__name__)
  148. del _int_type