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