]>
crepu.dev Git - config.git/blob - djavu-asus/emacs/elpy/rpc-venv/lib/python3.11/site-packages/mypy_extensions.py
1 """Defines experimental extensions to the standard "typing" module that are
2 supported by the mypy typechecker.
5 from mypy_extensions import TypedDict
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.
13 from typing
import _type_check
# type: ignore
16 def _check_fails(cls
, other
):
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):
26 def _dict_new(cls
, *args
, **kwargs
):
27 return dict(*args
, **kwargs
)
30 def _typeddict_new(cls
, _typename
, _fields
=None, **kwargs
):
31 total
= kwargs
.pop('total', True)
35 raise TypeError("TypedDict takes either a dict or keyword arguments,"
38 ns
= {'__annotations__': dict(_fields
), '__total__': total
}
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):
45 return _TypedDictMeta(_typename
, (), ns
)
48 class _TypedDictMeta(type):
49 def __new__(cls
, name
, bases
, ns
, total
=True):
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
56 ns
['__new__'] = _typeddict_new
if name
== 'TypedDict' else _dict_new
57 tp_dict
= super(_TypedDictMeta
, cls
).__new
__(cls
, name
, (dict,), ns
)
59 anns
= ns
.get('__annotations__', {})
60 msg
= "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
61 anns
= {n
: _type_check(tp
, msg
) for n
, tp
in anns
.items()}
63 anns
.update(base
.__dict
__.get('__annotations__', {}))
64 tp_dict
.__annotations
__ = anns
65 if not hasattr(tp_dict
, '__total__'):
66 tp_dict
.__total
__ = total
69 __instancecheck__
= __subclasscheck__
= _check_fails
72 TypedDict
= _TypedDictMeta('TypedDict', (dict,), {})
73 TypedDict
.__module
__ = __name__
75 """A simple typed name space. At runtime it is equivalent to a plain dict.
77 TypedDict creates a dictionary type that expects all of its
78 instances to have a certain set of keys, with each key
79 associated with a value of a consistent type. This expectation
80 is not checked at runtime but is only enforced by typecheckers.
83 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
84 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
85 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
86 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
88 The type info could be accessed via Point2D.__annotations__. TypedDict
89 supports two additional equivalent forms::
91 Point2D = TypedDict('Point2D', x=int, y=int, label=str)
93 class Point2D(TypedDict):
98 The latter syntax is only supported in Python 3.6+, while two other
99 syntax forms work for 3.2+
102 # Argument constructors for making more-detailed Callables. These all just
103 # return their type argument, to make them complete noops in terms of the
107 def Arg(type=Any
, name
=None):
108 """A normal positional argument"""
112 def DefaultArg(type=Any
, name
=None):
113 """A positional argument with a default value"""
117 def NamedArg(type=Any
, name
=None):
118 """A keyword-only argument"""
122 def DefaultNamedArg(type=Any
, name
=None):
123 """A keyword-only argument with a default value"""
127 def VarArg(type=Any
):
128 """A *args-style variadic positional argument"""
133 """A **kwargs-style variadic keyword argument"""
137 # Return type that indicates a function does not return
145 def mypyc_attr(*attrs
, **kwattrs
):
149 # TODO: We may want to try to properly apply this to any type
150 # variables left over...
151 class _FlexibleAliasClsApplied
:
152 def __init__(self
, val
):
155 def __getitem__(self
, args
):
159 class _FlexibleAliasCls
:
160 def __getitem__(self
, args
):
161 return _FlexibleAliasClsApplied(args
[-1])
164 FlexibleAlias
= _FlexibleAliasCls()
167 class _NativeIntMeta(type):
168 def __instancecheck__(cls
, inst
):
169 return isinstance(inst
, int)
175 class i64(metaclass
=_NativeIntMeta
):
176 def __new__(cls
, x
=0, base
=_sentinel
):
177 if base
is not _sentinel
:
182 class i32(metaclass
=_NativeIntMeta
):
183 def __new__(cls
, x
=0, base
=_sentinel
):
184 if base
is not _sentinel
:
189 class i16(metaclass
=_NativeIntMeta
):
190 def __new__(cls
, x
=0, base
=_sentinel
):
191 if base
is not _sentinel
:
196 class u8(metaclass
=_NativeIntMeta
):
197 def __new__(cls
, x
=0, base
=_sentinel
):
198 if base
is not _sentinel
:
203 for _int_type
in i64
, i32
, i16
, u8
:
204 _int_type
.__doc
__ = \
205 """A native fixed-width integer type when used with mypyc.
207 In code not compiled with mypyc, behaves like the 'int' type in these
210 * {name}(x[, base=n]) converts a number or string to 'int'
211 * isinstance(x, {name}) is the same as isinstance(x, int)
212 """.format(name
=_int_type
.__name
__)