From 76a42727abd8485fc9a2af2e711d583be26627bf Mon Sep 17 00:00:00 2001 From: funkyrailroad Date: Thu, 23 May 2024 11:56:09 -0400 Subject: [PATCH 1/3] Add datetime `__replace__` methods on 3.13+ (#12014) --- stdlib/@tests/stubtest_allowlists/py313.txt | 3 -- stdlib/datetime.pyi | 32 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/stdlib/@tests/stubtest_allowlists/py313.txt b/stdlib/@tests/stubtest_allowlists/py313.txt index f13eb48c1f21..f225bf6e0ab2 100644 --- a/stdlib/@tests/stubtest_allowlists/py313.txt +++ b/stdlib/@tests/stubtest_allowlists/py313.txt @@ -178,11 +178,8 @@ ctypes.sizeof ctypes.wintypes.PCHAR.from_param ctypes.wintypes.PWCHAR.from_param dataclasses.Field.__class_getitem__ -datetime.date.__replace__ datetime.date.fromisoformat -datetime.datetime.__replace__ datetime.datetime.fromisoformat -datetime.time.__replace__ datetime.time.fromisoformat datetime.timezone.dst datetime.timezone.fromutc diff --git a/stdlib/datetime.pyi b/stdlib/datetime.pyi index 7b890ca010dc..71522a59d4df 100644 --- a/stdlib/datetime.pyi +++ b/stdlib/datetime.pyi @@ -79,6 +79,9 @@ class date: def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... def toordinal(self) -> int: ... + if sys.version_info >= (3, 13): + def __replace__(self, /, *, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ... + def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ... def __le__(self, value: date, /) -> bool: ... def __lt__(self, value: date, /) -> bool: ... @@ -148,6 +151,19 @@ class time: def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... + if sys.version_info >= (3, 13): + def __replace__( + self, + /, + *, + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., + fold: int = ..., + ) -> Self: ... + def replace( self, hour: SupportsIndex = ..., @@ -263,6 +279,22 @@ class datetime(date): def date(self) -> _Date: ... def time(self) -> _Time: ... def timetz(self) -> _Time: ... + if sys.version_info >= (3, 13): + def __replace__( + self, + /, + *, + year: SupportsIndex = ..., + month: SupportsIndex = ..., + day: SupportsIndex = ..., + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., + fold: int = ..., + ) -> Self: ... + def replace( self, year: SupportsIndex = ..., From c11fc20651913acd99f6d42e4a9f3aa9eda036a3 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 23 May 2024 12:13:53 -0400 Subject: [PATCH 2/3] Small fix for pkg_resources StrPath (#12015) --- stubs/setuptools/pkg_resources/__init__.pyi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stubs/setuptools/pkg_resources/__init__.pyi b/stubs/setuptools/pkg_resources/__init__.pyi index 3e224ef60829..f31960dcf4d3 100644 --- a/stubs/setuptools/pkg_resources/__init__.pyi +++ b/stubs/setuptools/pkg_resources/__init__.pyi @@ -384,7 +384,7 @@ class Distribution(NullProvider): ) -> None: ... @classmethod def from_location( - cls, location: str, basename: str, metadata: _MetadataType = None, *, precedence: int = 3 + cls, location: str, basename: StrPath, metadata: _MetadataType = None, *, precedence: int = 3 ) -> Distribution: ... @property def hashcmp(self) -> tuple[parse_version, int, str, str | None, str, str]: ... @@ -405,7 +405,7 @@ class Distribution(NullProvider): def activate(self, path: list[str] | None = None, replace: bool = False) -> None: ... def egg_name(self) -> str: ... # type: ignore[override] # supertype's egg_name is a variable, not a method @classmethod - def from_filename(cls, filename: StrOrBytesPath, metadata: _MetadataType = None, *, precedence: int = 3) -> Distribution: ... + def from_filename(cls, filename: StrPath, metadata: _MetadataType = None, *, precedence: int = 3) -> Distribution: ... def as_requirement(self) -> Requirement: ... def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint: ... @overload From 4bc70e1e4d38875bd83a34205c1d0a06619b26fd Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Thu, 23 May 2024 13:08:18 -0400 Subject: [PATCH 3/3] Use mypy from git for stdlib stubtest (#12016) --- .github/workflows/daily.yml | 4 + .github/workflows/stubtest_stdlib.yml | 4 + .../stubtest_allowlists/darwin-py313.txt | 1 - stdlib/@tests/stubtest_allowlists/py313.txt | 163 ------------------ stdlib/builtins.pyi | 12 +- 5 files changed, 14 insertions(+), 170 deletions(-) diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml index 016c52eb0122..d1e17677f538 100644 --- a/.github/workflows/daily.yml +++ b/.github/workflows/daily.yml @@ -52,6 +52,8 @@ jobs: check-latest: true - name: Install dependencies run: pip install -r requirements-tests.txt + - name: Install mypy from git + run: pip install git+https://github.com/python/mypy@e8a26308d5d06925cf769b62f41ef2e4bc546ada - name: Run stubtest run: python tests/stubtest_stdlib.py @@ -70,6 +72,8 @@ jobs: check-latest: true - name: Install dependencies run: pip install -r requirements-tests.txt + - name: Install mypy from git + run: pip install git+https://github.com/python/mypy@e8a26308d5d06925cf769b62f41ef2e4bc546ada - name: Run stubtest run: python tests/stubtest_stdlib.py diff --git a/.github/workflows/stubtest_stdlib.yml b/.github/workflows/stubtest_stdlib.yml index 54cedbe05010..6007f1c39d92 100644 --- a/.github/workflows/stubtest_stdlib.yml +++ b/.github/workflows/stubtest_stdlib.yml @@ -48,6 +48,8 @@ jobs: check-latest: true - name: Install dependencies run: pip install -r requirements-tests.txt + - name: Install mypy from git + run: pip install git+https://github.com/python/mypy@e8a26308d5d06925cf769b62f41ef2e4bc546ada - name: Run stubtest run: python tests/stubtest_stdlib.py @@ -66,5 +68,7 @@ jobs: check-latest: true - name: Install dependencies run: pip install -r requirements-tests.txt + - name: Install mypy from git + run: pip install git+https://github.com/python/mypy@e8a26308d5d06925cf769b62f41ef2e4bc546ada - name: Run stubtest run: python tests/stubtest_stdlib.py diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py313.txt b/stdlib/@tests/stubtest_allowlists/darwin-py313.txt index 2189ddb83231..27f9132a115e 100644 --- a/stdlib/@tests/stubtest_allowlists/darwin-py313.txt +++ b/stdlib/@tests/stubtest_allowlists/darwin-py313.txt @@ -23,7 +23,6 @@ time.CLOCK_UPTIME_RAW_APPROX webbrowser.MacOSX _curses.A_ITALIC curses.A_ITALIC -_decimal.DecimalTuple.__replace__ # TODO: fix _curses.unget_wch diff --git a/stdlib/@tests/stubtest_allowlists/py313.txt b/stdlib/@tests/stubtest_allowlists/py313.txt index f225bf6e0ab2..16b96414911c 100644 --- a/stdlib/@tests/stubtest_allowlists/py313.txt +++ b/stdlib/@tests/stubtest_allowlists/py313.txt @@ -6,7 +6,6 @@ _ast.PyCF_OPTIMIZED_AST _collections_abc.dict_items.isdisjoint _collections_abc.dict_keys.isdisjoint -_ctypes.Array.__class_getitem__ _ctypes.POINTER _ctypes.addressof _ctypes.alignment @@ -30,29 +29,6 @@ _pyrepl.types _pyrepl.unix_console _pyrepl.unix_eventqueue _pyrepl.utils -_socket.close -_socket.dup -_socket.if_indextoname -_socket.setdefaulttimeout -_socket.socket.bind -_socket.socket.connect -_socket.socket.connect_ex -_socket.socket.setblocking -_socket.socket.settimeout -_socket.socket.shutdown -_stat.S_IFMT -_stat.S_IMODE -_stat.S_ISBLK -_stat.S_ISCHR -_stat.S_ISDIR -_stat.S_ISDOOR -_stat.S_ISFIFO -_stat.S_ISLNK -_stat.S_ISPORT -_stat.S_ISREG -_stat.S_ISSOCK -_stat.S_ISWHT -_stat.filemode _thread.interrupt_main _thread.lock _thread.stack_size @@ -61,9 +37,6 @@ _thread.start_new_thread _tkinter.TkappType.gettrace _tkinter.TkappType.settrace _tkinter.create -_weakref.ReferenceType.__class_getitem__ -_weakref.ref.__class_getitem__ -_weakrefset.WeakSet.__class_getitem__ argparse.Action.__init__ argparse.BooleanOptionalAction.__init__ argparse._AppendAction.__init__ @@ -76,21 +49,17 @@ argparse._StoreFalseAction.__init__ argparse._StoreTrueAction.__init__ argparse._SubParsersAction.add_parser argparse._VersionAction.__init__ -array.array.__class_getitem__ ast.PyCF_OPTIMIZED_AST asyncio.AbstractEventLoop.create_server asyncio.AbstractServer.abort_clients asyncio.AbstractServer.close_clients asyncio.BaseEventLoop.create_server asyncio.EventLoop -asyncio.Future.__class_getitem__ -asyncio.Queue.__class_getitem__ asyncio.Queue.shutdown asyncio.QueueShutDown asyncio.Server.abort_clients asyncio.Server.close_clients asyncio.StreamWriter.__del__ -asyncio.Task.__class_getitem__ asyncio.base_events.BaseEventLoop.create_server asyncio.base_events.Server.abort_clients asyncio.base_events.Server.close_clients @@ -100,53 +69,27 @@ asyncio.events.AbstractServer.close_clients asyncio.format_helpers._format_args_and_kwargs asyncio.format_helpers._format_callback asyncio.format_helpers._format_callback_source -asyncio.futures.Future.__class_getitem__ -asyncio.queues.Queue.__class_getitem__ asyncio.queues.Queue.shutdown asyncio.queues.QueueShutDown asyncio.queues.__all__ asyncio.streams.StreamWriter.__del__ -asyncio.tasks.Task.__class_getitem__ asyncio.unix_events.EventLoop asyncio.unix_events._UnixSelectorEventLoop.create_unix_server asyncio.unix_events.__all__ bdb.Bdb.dispatch_opcode bdb.Bdb.set_stepinstr bdb.Bdb.user_opcode -builtins.ExceptionGroup.split -builtins.ExceptionGroup.subgroup builtins.IncompleteInputError builtins.PythonFinalizationError -builtins.dict.__class_getitem__ -builtins.enumerate.__class_getitem__ -builtins.frozenset.__class_getitem__ -builtins.list.__class_getitem__ builtins.property.__name__ -builtins.property.deleter -builtins.property.getter -builtins.property.setter -builtins.range.count -builtins.range.index -builtins.set.__class_getitem__ -builtins.set.add -builtins.set.discard -builtins.set.remove -builtins.slice.indices builtins.str.format_map builtins.str.replace -builtins.tuple.__class_getitem__ codecs.backslashreplace_errors codecs.ignore_errors codecs.namereplace_errors codecs.replace_errors codecs.strict_errors codecs.xmlcharrefreplace_errors -collections.defaultdict.__class_getitem__ -collections.deque.__class_getitem__ -concurrent.futures.Future.__class_getitem__ -concurrent.futures._base.DoneAndNotDoneFutures.__replace__ -concurrent.futures._base.Future.__class_getitem__ -concurrent.futures.thread._WorkItem.__class_getitem__ configparser.LegacyInterpolation configparser.MultilineContinuationError configparser.ParsingError.__init__ @@ -154,12 +97,6 @@ configparser.ParsingError.combine configparser.RawConfigParser.__init__ configparser.UNNAMED_SECTION configparser.__all__ -contextvars.ContextVar.__class_getitem__ -contextvars.Token.__class_getitem__ -csv.DictReader.__class_getitem__ -csv.DictWriter.__class_getitem__ -ctypes.Array.__class_getitem__ -ctypes.LibraryLoader.__class_getitem__ ctypes.POINTER ctypes._endian.DEFAULT_MODE ctypes._endian.RTLD_GLOBAL @@ -177,22 +114,7 @@ ctypes.pointer ctypes.sizeof ctypes.wintypes.PCHAR.from_param ctypes.wintypes.PWCHAR.from_param -dataclasses.Field.__class_getitem__ -datetime.date.fromisoformat -datetime.datetime.fromisoformat -datetime.time.fromisoformat -datetime.timezone.dst -datetime.timezone.fromutc -datetime.timezone.tzname -datetime.timezone.utcoffset -datetime.tzinfo.dst -datetime.tzinfo.fromutc -datetime.tzinfo.tzname -datetime.tzinfo.utcoffset dbm.sqlite3 -decimal.DecimalTuple.__replace__ -difflib.Match.__replace__ -difflib.SequenceMatcher.__class_getitem__ dis.Bytecode.__init__ dis.Instruction._disassemble dis.Instruction.baseopcode @@ -202,8 +124,6 @@ dis.Instruction.end_offset dis.Instruction.is_jump_target dis.Instruction.jump_target dis.Instruction.oparg -dis.Positions.__replace__ -dis._Instruction.__replace__ dis.__all__ dis.dis dis.disassemble @@ -217,17 +137,9 @@ email.utils.parseaddr enum.EnumDict enum._EnumDict.member_names enum.__all__ -filecmp.dircmp.__class_getitem__ filecmp.dircmp.__init__ -fileinput.FileInput.__class_getitem__ -functools._CacheInfo.__replace__ -functools.cached_property.__class_getitem__ -functools.partial.__class_getitem__ -functools.partialmethod.__class_getitem__ glob.__all__ glob.translate -graphlib.TopologicalSorter.__class_getitem__ -http.cookies.Morsel.__class_getitem__ importlib.metadata.DeprecatedTuple importlib.metadata.Distribution.origin importlib.metadata.MetadataPathFinder.invalidate_caches @@ -245,29 +157,17 @@ importlib.resources.open_text importlib.resources.path importlib.resources.read_binary importlib.resources.read_text -inspect.ArgInfo.__replace__ -inspect.Arguments.__replace__ -inspect.Attribute.__replace__ -inspect.ClosureVars.__replace__ -inspect.FullArgSpec.__replace__ -inspect._FrameInfo.__replace__ -inspect._Traceback.__replace__ io.IOBase._checkClosed ipaddress.IPv4Address.ipv6_mapped -itertools.chain.__class_getitem__ json.encoder.encode_basestring json.encoder.encode_basestring_ascii locale.resetlocale -logging.LoggerAdapter.__class_getitem__ -logging.StreamHandler.__class_getitem__ -mailbox.Mailbox.__class_getitem__ mailbox.Maildir.add_flag mailbox.Maildir.get_flags mailbox.Maildir.get_info mailbox.Maildir.remove_flag mailbox.Maildir.set_flags mailbox.Maildir.set_info -mailbox._ProxyFile.__class_getitem__ math.fma mimetypes.MimeTypes.guess_file_type mimetypes.__all__ @@ -275,16 +175,9 @@ mimetypes.guess_file_type mmap.MAP_32BIT mmap.mmap.seekable mmap.MAP_NORESERVE -multiprocessing.dummy.Queue.__class_getitem__ multiprocessing.managers.DictProxy.__class_getitem__ multiprocessing.managers.ListProxy.__class_getitem__ -multiprocessing.managers.ValueProxy.__class_getitem__ -multiprocessing.pool.ApplyResult.__class_getitem__ -multiprocessing.queues.Queue.__class_getitem__ -multiprocessing.queues.SimpleQueue.__class_getitem__ -multiprocessing.shared_memory.ShareableList.__class_getitem__ multiprocessing.shared_memory.SharedMemory.__init__ -os.DirEntry.__class_getitem__ os.grantpt os.posix_openpt os.ptsname @@ -312,12 +205,10 @@ pdb.Pdb.execRcLines pdb.Pdb.interaction pdb.Pdb.message pdb.Pdb.user_opcode -pkgutil.ModuleInfo.__replace__ platform.AndroidVer platform.IOSVersionInfo platform.android_ver platform.ios_ver -posix.DirEntry.__class_getitem__ posix.grantpt posix.posix_openpt posix.ptsname @@ -338,49 +229,17 @@ pydoc.pipepager pydoc.plainpager pydoc.tempfilepager pydoc.ttypager -queue.Queue.__class_getitem__ -queue.SimpleQueue.__class_getitem__ -re.Match.__class_getitem__ -re.Pattern.__class_getitem__ readline.backend -sched.Event.__replace__ -selectors.SelectorKey.__replace__ -shutil._ntuple_diskusage.__replace__ site.gethistoryfile site.register_readline -socket.close -socket.dup -socket.if_indextoname -socket.setdefaulttimeout sqlite3.Connection.iterdump sqlite3.dbapi2.Connection.iterdump sre_compile.SRE_FLAG_TEMPLATE sre_constants.SRE_FLAG_TEMPLATE sre_parse.SRE_FLAG_TEMPLATE -ssl.DefaultVerifyPaths.__replace__ -stat.S_IFMT -stat.S_IMODE -stat.S_ISBLK -stat.S_ISCHR -stat.S_ISDIR -stat.S_ISDOOR -stat.S_ISFIFO -stat.S_ISLNK -stat.S_ISPORT -stat.S_ISREG -stat.S_ISSOCK -stat.S_ISWHT -stat.filemode -statistics.LinearRegression.__replace__ -subprocess.CompletedProcess.__class_getitem__ -subprocess.Popen.__class_getitem__ tarfile.TarFile.__init__ -tempfile.SpooledTemporaryFile.__class_getitem__ -tempfile.TemporaryDirectory.__class_getitem__ threading.stack_size time.clock_gettime_ns -time.mktime -time.sleep tkinter.Misc.after_info tkinter.Misc.busy tkinter.Misc.busy_cget @@ -418,14 +277,9 @@ traceback.format_exception_only turtle.RawTurtle.settiltangle turtle.__all__ turtle.settiltangle -types.AsyncGeneratorType.__class_getitem__ -types.AsyncGeneratorType.asend types.CodeType.__replace__ types.CoroutineType.__class_getitem__ -types.CoroutineType.send types.GeneratorType.__class_getitem__ -types.GeneratorType.send -types.MappingProxyType.__class_getitem__ types.MappingProxyType.get types.SimpleNamespace.__replace__ typing.ForwardRef._evaluate @@ -440,9 +294,7 @@ typing_extensions.TypeIs unittest.IsolatedAsyncioTestCase.loop_factory unittest.TestProgram.usageExit unittest.__all__ -unittest._log._LoggingWatcher.__replace__ unittest.async_case.IsolatedAsyncioTestCase.loop_factory -unittest.case._AssertRaisesContext.__class_getitem__ unittest.findTestCases unittest.getTestCaseNames unittest.loader.findTestCases @@ -453,24 +305,9 @@ unittest.makeSuite unittest.mock.NonCallableMock._calls_repr unittest.mock.ThreadingMock unittest.mock.__all__ -urllib.parse._DefragResultBase.__replace__ -urllib.parse._NetlocResultMixinBase.__class_getitem__ -urllib.parse._ParseResultBase.__replace__ -urllib.parse._SplitResultBase.__replace__ -urllib.robotparser.RequestRate.__replace__ -wave._wave_params.__replace__ -weakref.ReferenceType.__class_getitem__ -weakref.WeakSet.__class_getitem__ -weakref.ref.__class_getitem__ zipfile.CompleteDirs.inject zipfile.ZipInfo.compress_level zipfile._path.CompleteDirs.inject -zoneinfo.ZoneInfo.fromutc - -# These attributes exist on all Python classes on py313+ -# (Stubtest handles this on mypy master) -.*\.__firstlineno__ -.*\.__static_attributes__ # ====================================== # Pre-existing errors from Python <=3.12 diff --git a/stdlib/builtins.pyi b/stdlib/builtins.pyi index e8beea420eaa..ab73371e7910 100644 --- a/stdlib/builtins.pyi +++ b/stdlib/builtins.pyi @@ -1844,11 +1844,11 @@ class BaseException: __traceback__: TracebackType | None def __init__(self, *args: object) -> None: ... def __setstate__(self, state: dict[str, Any] | None, /) -> None: ... - def with_traceback(self, object: TracebackType | None, /) -> Self: ... + def with_traceback(self, tb: TracebackType | None, /) -> Self: ... if sys.version_info >= (3, 11): # only present after add_note() is called __notes__: list[str] - def add_note(self, object: str, /) -> None: ... + def add_note(self, note: str, /) -> None: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... @@ -2008,7 +2008,7 @@ if sys.version_info >= (3, 11): def exceptions(self) -> tuple[_BaseExceptionT_co | BaseExceptionGroup[_BaseExceptionT_co], ...]: ... @overload def subgroup( - self, object: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + self, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / ) -> ExceptionGroup[_ExceptionT] | None: ... @overload def subgroup( @@ -2020,7 +2020,7 @@ if sys.version_info >= (3, 11): ) -> BaseExceptionGroup[_BaseExceptionT_co] | None: ... @overload def split( - self, object: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + self, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / ) -> tuple[ExceptionGroup[_ExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... @overload def split( @@ -2032,10 +2032,10 @@ if sys.version_info >= (3, 11): ) -> tuple[BaseExceptionGroup[_BaseExceptionT_co] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... # In reality it is `NonEmptySequence`: @overload - def derive(self, object: Sequence[_ExceptionT], /) -> ExceptionGroup[_ExceptionT]: ... + def derive(self, excs: Sequence[_ExceptionT], /) -> ExceptionGroup[_ExceptionT]: ... @overload def derive(self, excs: Sequence[_BaseExceptionT], /) -> BaseExceptionGroup[_BaseExceptionT]: ... - def __class_getitem__(cls, object: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): def __new__(cls, message: str, exceptions: Sequence[_ExceptionT_co], /) -> Self: ...