1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
|
"""Defines experimental extensions to the standard "typing" module that are
supported by the mypy typechecker.
Example usage:
from mypy_extensions import TypedDict
"""
from typing import Any, Dict
import sys
# _type_check is NOT a part of public typing API, it is used here only to mimic
# the (convenient) behavior of types provided by typing module.
from typing import _type_check # type: ignore
def _check_fails(cls, other):
try:
if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools', 'typing']:
# Typed dicts are only for static structural subtyping.
raise TypeError('TypedDict does not support instance and class checks')
except (AttributeError, ValueError):
pass
return False
def _dict_new(cls, *args, **kwargs):
return dict(*args, **kwargs)
def _typeddict_new(cls, _typename, _fields=None, **kwargs):
total = kwargs.pop('total', True)
if _fields is None:
_fields = kwargs
elif kwargs:
raise TypeError("TypedDict takes either a dict or keyword arguments,"
" but not both")
ns = {'__annotations__': dict(_fields), '__total__': total}
try:
# Setting correct module is necessary to make typed dict classes pickleable.
ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return _TypedDictMeta(_typename, (), ns, _from_functional_call=True)
class _TypedDictMeta(type):
def __new__(cls, name, bases, ns, total=True, _from_functional_call=False):
# Create new typed dict class object.
# This method is called directly when TypedDict is subclassed,
# or via _typeddict_new when TypedDict is instantiated. This way
# TypedDict supports all three syntaxes described in its docstring.
# Subclasses and instances of TypedDict return actual dictionaries
# via _dict_new.
# We need the `if TypedDict in globals()` check,
# or we emit a DeprecationWarning when creating mypy_extensions.TypedDict itself
if 'TypedDict' in globals():
import warnings
warnings.warn(
(
"mypy_extensions.TypedDict is deprecated, "
"and will be removed in a future version. "
"Use typing.TypedDict or typing_extensions.TypedDict instead."
),
DeprecationWarning,
stacklevel=(3 if _from_functional_call else 2)
)
ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
anns = ns.get('__annotations__', {})
msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
anns = {n: _type_check(tp, msg) for n, tp in anns.items()}
for base in bases:
anns.update(base.__dict__.get('__annotations__', {}))
tp_dict.__annotations__ = anns
if not hasattr(tp_dict, '__total__'):
tp_dict.__total__ = total
return tp_dict
__instancecheck__ = __subclasscheck__ = _check_fails
TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
TypedDict.__module__ = __name__
TypedDict.__doc__ = \
"""A simple typed name space. At runtime it is equivalent to a plain dict.
TypedDict creates a dictionary type that expects all of its
instances to have a certain set of keys, with each key
associated with a value of a consistent type. This expectation
is not checked at runtime but is only enforced by typecheckers.
Usage::
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
The type info could be accessed via Point2D.__annotations__. TypedDict
supports two additional equivalent forms::
Point2D = TypedDict('Point2D', x=int, y=int, label=str)
class Point2D(TypedDict):
x: int
y: int
label: str
The latter syntax is only supported in Python 3.6+, while two other
syntax forms work for 3.2+
"""
# Argument constructors for making more-detailed Callables. These all just
# return their type argument, to make them complete noops in terms of the
# `typing` module.
def Arg(type=Any, name=None):
"""A normal positional argument"""
return type
def DefaultArg(type=Any, name=None):
"""A positional argument with a default value"""
return type
def NamedArg(type=Any, name=None):
"""A keyword-only argument"""
return type
def DefaultNamedArg(type=Any, name=None):
"""A keyword-only argument with a default value"""
return type
def VarArg(type=Any):
"""A *args-style variadic positional argument"""
return type
def KwArg(type=Any):
"""A **kwargs-style variadic keyword argument"""
return type
# Return type that indicates a function does not return
# Deprecated, use typing or typing_extensions variants instead
class _DEPRECATED_NoReturn: pass
def trait(cls):
return cls
def mypyc_attr(*attrs, **kwattrs):
return lambda x: x
# TODO: We may want to try to properly apply this to any type
# variables left over...
class _FlexibleAliasClsApplied:
def __init__(self, val):
self.val = val
def __getitem__(self, args):
return self.val
class _FlexibleAliasCls:
def __getitem__(self, args):
return _FlexibleAliasClsApplied(args[-1])
FlexibleAlias = _FlexibleAliasCls()
class _NativeIntMeta(type):
def __instancecheck__(cls, inst):
return isinstance(inst, int)
_sentinel = object()
class i64(metaclass=_NativeIntMeta):
def __new__(cls, x=0, base=_sentinel):
if base is not _sentinel:
return int(x, base)
return int(x)
class i32(metaclass=_NativeIntMeta):
def __new__(cls, x=0, base=_sentinel):
if base is not _sentinel:
return int(x, base)
return int(x)
class i16(metaclass=_NativeIntMeta):
def __new__(cls, x=0, base=_sentinel):
if base is not _sentinel:
return int(x, base)
return int(x)
class u8(metaclass=_NativeIntMeta):
def __new__(cls, x=0, base=_sentinel):
if base is not _sentinel:
return int(x, base)
return int(x)
for _int_type in i64, i32, i16, u8:
_int_type.__doc__ = \
"""A native fixed-width integer type when used with mypyc.
In code not compiled with mypyc, behaves like the 'int' type in these
runtime contexts:
* {name}(x[, base=n]) converts a number or string to 'int'
* isinstance(x, {name}) is the same as isinstance(x, int)
""".format(name=_int_type.__name__)
del _int_type
def _warn_deprecation(name: str, module_globals: Dict[str, Any]) -> Any:
if (val := module_globals.get(f"_DEPRECATED_{name}")) is None:
msg = f"module '{__name__}' has no attribute '{name}'"
raise AttributeError(msg)
module_globals[name] = val
if name in {"NoReturn"}:
msg = (
f"'mypy_extensions.{name}' is deprecated, "
"and will be removed in a future version. "
f"Use 'typing.{name}' or 'typing_extensions.{name}' instead"
)
else:
assert False, f"Add deprecation message for 'mypy_extensions.{name}'"
import warnings
warnings.warn(msg, DeprecationWarning, stacklevel=3)
return val
def __getattr__(name: str) -> Any:
return _warn_deprecation(name, module_globals=globals())
|