././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1575461837.3507211 mypy_extensions-1.2.0/LICENSE0000644000000000000000000000226413571721715012737 0ustar00Mypy extensions are licensed under the terms of the MIT license, reproduced below. = = = = = The MIT License Copyright (c) 2016-2017 Jukka Lehtosalo and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. = = = = = ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1745330889.723227 mypy_extensions-1.2.0/README.md0000644000000000000000000000030415001721312013161 0ustar00Mypy Extensions =============== The `mypy_extensions` module defines extensions to the Python standard library `typing` module that are supported by the mypy type checker and the mypyc compiler. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1793721780.892644 mypy_extensions-1.2.0/mypy_extensions.py0000644000000000000000000002114115272402665015554 0ustar00"""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) def _get_own_annotations(tp): if sys.version_info >= (3, 14): import annotationlib return annotationlib.get_annotations(tp) return tp.__dict__.get('__annotations__', {}) 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) if '__annotations__' in ns: anns = ns['__annotations__'] else: # Python 3.14+ evaluates class annotations lazily (PEP 649) anns = _get_own_annotations(tp_dict) 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(_get_own_annotations(base)) 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 i8(metaclass=_NativeIntMeta): def __new__(cls, x=0, base=_sentinel): if base is not _sentinel: return int(x, base) return int(x) class u64(metaclass=_NativeIntMeta): def __new__(cls, x=0, base=_sentinel): if base is not _sentinel: return int(x, base) return int(x) class u32(metaclass=_NativeIntMeta): def __new__(cls, x=0, base=_sentinel): if base is not _sentinel: return int(x, base) return int(x) class u16(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, i8, u64, u32, u16, 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()) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1793721933.6635685 mypy_extensions-1.2.0/pyproject.toml0000644000000000000000000000200115272403116014623 0ustar00[build-system] requires = ["flit_core>=3.11,<5"] build-backend = "flit_core.buildapi" [project] name = "mypy_extensions" version = "1.2.0" description = "Type system extensions for programs checked with the mypy type checker." readme = "README.md" authors = [ {name = "The mypy developers", email = "jukka.lehtosalo@iki.fi"} ] license = "MIT" classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", "Topic :: Software Development", ] requires-python = ">=3.10" [project.urls] Homepage = "https://github.com/python/mypy_extensions" [tool.flit.sdist] include = ["tox.ini", "*/*test*.py"] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1793721780.8930473 mypy_extensions-1.2.0/tests/testextensions.py0000644000000000000000000001765515272402665016557 0ustar00import collections.abc import pickle import sys import typing import warnings from contextlib import contextmanager from unittest import TestCase, main from mypy_extensions import TypedDict, i64, i32, i16, i8, u64, u32, u16, u8 class BaseTestCase(TestCase): def assertIsSubclass(self, cls, class_or_tuple, msg=None): if not issubclass(cls, class_or_tuple): message = '%r is not a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def assertNotIsSubclass(self, cls, class_or_tuple, msg=None): if issubclass(cls, class_or_tuple): message = '%r is a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=DeprecationWarning) Label = TypedDict('Label', [('label', str)]) class Point2D(TypedDict): x: int y: int class LabelPoint2D(Point2D, Label): ... class Options(TypedDict, total=False): log_level: int log_path: str class TypedDictTests(BaseTestCase): @contextmanager def assert_typeddict_deprecated(self): with self.assertWarnsRegex( DeprecationWarning, "mypy_extensions.TypedDict is deprecated" ): yield def test_basics_iterable_syntax(self): with self.assert_typeddict_deprecated(): Emp = TypedDict('Emp', {'name': str, 'id': int}) self.assertIsSubclass(Emp, dict) self.assertIsSubclass(Emp, typing.MutableMapping) self.assertNotIsSubclass(Emp, collections.abc.Sequence) jim = Emp(name='Jim', id=1) self.assertIs(type(jim), dict) self.assertEqual(jim['name'], 'Jim') self.assertEqual(jim['id'], 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp.__module__, __name__) self.assertEqual(Emp.__bases__, (dict,)) self.assertEqual(Emp.__annotations__, {'name': str, 'id': int}) self.assertEqual(Emp.__total__, True) def test_basics_keywords_syntax(self): with self.assert_typeddict_deprecated(): Emp = TypedDict('Emp', name=str, id=int) self.assertIsSubclass(Emp, dict) self.assertIsSubclass(Emp, typing.MutableMapping) self.assertNotIsSubclass(Emp, collections.abc.Sequence) jim = Emp(name='Jim', id=1) # type: ignore # mypy doesn't support keyword syntax yet self.assertIs(type(jim), dict) self.assertEqual(jim['name'], 'Jim') self.assertEqual(jim['id'], 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp.__module__, __name__) self.assertEqual(Emp.__bases__, (dict,)) self.assertEqual(Emp.__annotations__, {'name': str, 'id': int}) self.assertEqual(Emp.__total__, True) def test_typeddict_errors(self): with self.assert_typeddict_deprecated(): Emp = TypedDict('Emp', {'name': str, 'id': int}) self.assertEqual(TypedDict.__module__, 'mypy_extensions') jim = Emp(name='Jim', id=1) with self.assertRaises(TypeError): isinstance({}, Emp) # type: ignore with self.assertRaises(TypeError): isinstance(jim, Emp) # type: ignore with self.assertRaises(TypeError): issubclass(dict, Emp) # type: ignore with self.assertRaises(TypeError), self.assert_typeddict_deprecated(): TypedDict('Hi', x=()) with self.assertRaises(TypeError), self.assert_typeddict_deprecated(): TypedDict('Hi', [('x', int), ('y', ())]) with self.assertRaises(TypeError): TypedDict('Hi', [('x', int)], y=int) def test_py36_class_syntax_usage(self): self.assertEqual(LabelPoint2D.__name__, 'LabelPoint2D') # noqa self.assertEqual(LabelPoint2D.__module__, __name__) # noqa self.assertEqual(LabelPoint2D.__annotations__, {'x': int, 'y': int, 'label': str}) # noqa self.assertEqual(LabelPoint2D.__bases__, (dict,)) # noqa self.assertEqual(LabelPoint2D.__total__, True) # noqa self.assertNotIsSubclass(LabelPoint2D, typing.Sequence) # noqa not_origin = Point2D(x=0, y=1) # noqa self.assertEqual(not_origin['x'], 0) self.assertEqual(not_origin['y'], 1) other = LabelPoint2D(x=0, y=1, label='hi') # noqa self.assertEqual(other['label'], 'hi') def test_py36_class_usage_emits_deprecations(self): with self.assert_typeddict_deprecated(): class Foo(TypedDict): bar: int def test_pickle(self): global EmpD # pickle wants to reference the class by name with self.assert_typeddict_deprecated(): EmpD = TypedDict('EmpD', name=str, id=int) jane = EmpD({'name': 'jane', 'id': 37}) for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(jane, proto) jane2 = pickle.loads(z) self.assertEqual(jane2, jane) self.assertEqual(jane2, {'name': 'jane', 'id': 37}) ZZ = pickle.dumps(EmpD, proto) EmpDnew = pickle.loads(ZZ) self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane) def test_optional(self): with self.assert_typeddict_deprecated(): EmpD = TypedDict('EmpD', name=str, id=int) self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD]) self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD]) def test_total(self): with self.assert_typeddict_deprecated(): D = TypedDict('D', {'x': int}, total=False) self.assertEqual(D(), {}) self.assertEqual(D(x=1), {'x': 1}) self.assertEqual(D.__total__, False) self.assertEqual(Options(), {}) # noqa self.assertEqual(Options(log_level=2), {'log_level': 2}) # noqa self.assertEqual(Options.__total__, False) # noqa native_int_types = [i64, i32, i16, i8, u64, u32, u16, u8] class MypycNativeIntTests(TestCase): def test_construction(self): for native_int in native_int_types: self.assert_same(native_int(), 0) self.assert_same(native_int(0), 0) self.assert_same(native_int(1), 1) self.assert_same(native_int(-3), -3) self.assert_same(native_int(2**64), 2**64) self.assert_same(native_int(-2**64), -2**64) self.assert_same(native_int(1.234), 1) self.assert_same(native_int(2.634), 2) self.assert_same(native_int(-1.234), -1) self.assert_same(native_int(-2.634), -2) self.assert_same(native_int("0"), 0) self.assert_same(native_int("123"), 123) self.assert_same(native_int("abc", 16), 2748) self.assert_same(native_int("-101", base=2), -5) def test_isinstance(self): for native_int in native_int_types: assert isinstance(0, native_int) assert isinstance(1234, native_int) assert isinstance(True, native_int) assert not isinstance(1.0, native_int) def test_docstring(self): for native_int in native_int_types: # Just check that a docstring exists assert native_int.__doc__ def assert_same(self, x, y): assert type(x) is type(y) assert x == y class DeprecationTests(TestCase): def test_no_return_deprecation(self): del sys.modules["mypy_extensions"] with self.assertWarnsRegex( DeprecationWarning, "'mypy_extensions.NoReturn' is deprecated" ): import mypy_extensions mypy_extensions.NoReturn del sys.modules["mypy_extensions"] with self.assertWarnsRegex( DeprecationWarning, "'mypy_extensions.NoReturn' is deprecated" ): from mypy_extensions import NoReturn # noqa: F401 if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1793631913.452103 mypy_extensions-1.2.0/tox.ini0000644000000000000000000000073015272123251013230 0ustar00[tox] minversion = 4.4.4 skip_missing_interpreters = true envlist = py310, py311, py312, py313, py314, py315 [testenv] description = run the test driver with {basepython} commands = python -We -m unittest discover tests [testenv:lint] description = check the code style basepython = python3 deps = flake8 commands = flake8 -j0 {posargs} [flake8] max-line-length = 99 ignore = # multiple statements on one line (colon) (we use this for classes with empty body) E701 mypy_extensions-1.2.0/PKG-INFO0000644000000000000000000000215400000000000012755 0ustar00Metadata-Version: 2.5 Name: mypy_extensions Version: 1.2.0 Summary: Type system extensions for programs checked with the mypy type checker. Author-email: The mypy developers Requires-Python: >=3.10 Description-Content-Type: text/markdown License-Expression: MIT Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 Classifier: Programming Language :: Python :: 3.15 Classifier: Topic :: Software Development License-File: LICENSE Project-URL: Homepage, https://github.com/python/mypy_extensions Import-Name: mypy_extensions Mypy Extensions =============== The `mypy_extensions` module defines extensions to the Python standard library `typing` module that are supported by the mypy type checker and the mypyc compiler.