Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
mypy_extensions.py252 linesDownload Raw Back to site-packages
1"""Defines experimental extensions to the standard "typing" module that are2supported by the mypy typechecker.3 4Example usage:5    from mypy_extensions import TypedDict6"""7 8from typing import Any, Dict9 10import sys11# _type_check is NOT a part of public typing API, it is used here only to mimic12# the (convenient) behavior of types provided by typing module.13from typing import _type_check  # type: ignore14 15 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        pass23    return False24 25 26def _dict_new(cls, *args, **kwargs):27    return dict(*args, **kwargs)28 29 30def _typeddict_new(cls, _typename, _fields=None, **kwargs):31    total = kwargs.pop('total', True)32    if _fields is None:33        _fields = kwargs34    elif kwargs:35        raise TypeError("TypedDict takes either a dict or keyword arguments,"36                        " but not both")37 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        pass44 45    return _TypedDictMeta(_typename, (), ns, _from_functional_call=True)46 47 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 way53        # TypedDict supports all three syntaxes described in its docstring.54        # Subclasses and instances of TypedDict return actual dictionaries55        # via _dict_new.56 57        # We need the `if TypedDict in globals()` check,58        # or we emit a DeprecationWarning when creating mypy_extensions.TypedDict itself59        if 'TypedDict' in globals():60            import warnings61            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            )70 71        ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new72        tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)73 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__ = anns80        if not hasattr(tp_dict, '__total__'):81            tp_dict.__total__ = total82        return tp_dict83 84    __instancecheck__ = __subclasscheck__ = _check_fails85 86 87TypedDict = _TypedDictMeta('TypedDict', (dict,), {})88TypedDict.__module__ = __name__89TypedDict.__doc__ = \90    """A simple typed name space. At runtime it is equivalent to a plain dict.91 92    TypedDict creates a dictionary type that expects all of its93    instances to have a certain set of keys, with each key94    associated with a value of a consistent type. This expectation95    is not checked at runtime but is only enforced by typecheckers.96    Usage::97 98        Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})99        a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK100        b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check101        assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')102 103    The type info could be accessed via Point2D.__annotations__. TypedDict104    supports two additional equivalent forms::105 106        Point2D = TypedDict('Point2D', x=int, y=int, label=str)107 108        class Point2D(TypedDict):109            x: int110            y: int111            label: str112 113    The latter syntax is only supported in Python 3.6+, while two other114    syntax forms work for 3.2+115    """116 117# Argument constructors for making more-detailed Callables. These all just118# return their type argument, to make them complete noops in terms of the119# `typing` module.120 121 122def Arg(type=Any, name=None):123    """A normal positional argument"""124    return type125 126 127def DefaultArg(type=Any, name=None):128    """A positional argument with a default value"""129    return type130 131 132def NamedArg(type=Any, name=None):133    """A keyword-only argument"""134    return type135 136 137def DefaultNamedArg(type=Any, name=None):138    """A keyword-only argument with a default value"""139    return type140 141 142def VarArg(type=Any):143    """A *args-style variadic positional argument"""144    return type145 146 147def KwArg(type=Any):148    """A **kwargs-style variadic keyword argument"""149    return type150 151 152# Return type that indicates a function does not return153# Deprecated, use typing or typing_extensions variants instead154class _DEPRECATED_NoReturn: pass155 156 157def trait(cls):158    return cls159 160 161def mypyc_attr(*attrs, **kwattrs):162    return lambda x: x163 164 165# TODO: We may want to try to properly apply this to any type166# variables left over...167class _FlexibleAliasClsApplied:168    def __init__(self, val):169        self.val = val170 171    def __getitem__(self, args):172        return self.val173 174 175class _FlexibleAliasCls:176    def __getitem__(self, args):177        return _FlexibleAliasClsApplied(args[-1])178 179 180FlexibleAlias = _FlexibleAliasCls()181 182 183class _NativeIntMeta(type):184    def __instancecheck__(cls, inst):185        return isinstance(inst, int)186 187 188_sentinel = object()189 190 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)196 197 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)203 204 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)210 211 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)217 218 219for _int_type in i64, i32, i16, u8:220    _int_type.__doc__ = \221        """A native fixed-width integer type when used with mypyc.222 223        In code not compiled with mypyc, behaves like the 'int' type in these224        runtime contexts:225 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_type230 231 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] = val237    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 warnings246    warnings.warn(msg, DeprecationWarning, stacklevel=3)247    return val248 249 250def __getattr__(name: str) -> Any:251    return _warn_deprecation(name, module_globals=globals())252 
codekingpro/portable-devtools · Team Ai