diff options
84 files changed, 408 insertions, 210 deletions
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 9b7a403..fae5138 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -26,8 +26,8 @@ Objects/dict* @methane # Ignoring importlib.h so as to not get flagged on # all pull requests that change the emitted # bytecode. -**/*import*.c @python/import-team -**/*import*.py @python/import-team +**/*import*.c @brettcannon @encukou @ericsnowcurrently @ncoghlan @warsaw +**/*import*.py @brettcannon @encukou @ericsnowcurrently @ncoghlan @warsaw # SSL diff --git a/Doc/library/email.generator.rst b/Doc/library/email.generator.rst index fc535a3..c09ae8c 100644 --- a/Doc/library/email.generator.rst +++ b/Doc/library/email.generator.rst @@ -188,7 +188,7 @@ to be using :class:`BytesGenerator`, and not :class:`Generator`. (This is required because strings cannot represent non-ASCII bytes.) Convert any bytes with the high bit set as needed using an ASCII-compatible :mailheader:`Content-Transfer-Encoding`. That is, - transform parts with non-ASCII :mailheader:`Cotnent-Transfer-Encoding` + transform parts with non-ASCII :mailheader:`Content-Transfer-Encoding` (:mailheader:`Content-Transfer-Encoding: 8bit`) to an ASCII compatible :mailheader:`Content-Transfer-Encoding`, and encode RFC-invalid non-ASCII bytes in headers using the MIME ``unknown-8bit`` character set, thus diff --git a/Doc/library/pyclbr.rst b/Doc/library/pyclbr.rst index a70c8df..b80a2fa 100644 --- a/Doc/library/pyclbr.rst +++ b/Doc/library/pyclbr.rst @@ -44,7 +44,7 @@ modules. .. versionadded:: 3.7 Descriptors for nested definitions. They are accessed through the - new children attibute. Each has a new parent attribute. + new children attribute. Each has a new parent attribute. The descriptors returned by these functions are instances of Function and Class classes. Users are not expected to create instances diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst index 6a44198..20f5724 100644 --- a/Doc/library/ssl.rst +++ b/Doc/library/ssl.rst @@ -665,7 +665,7 @@ Constants .. data:: PROTOCOL_SSLv23 - Alias for data:`PROTOCOL_TLS`. + Alias for :data:`PROTOCOL_TLS`. .. deprecated:: 3.6 @@ -1821,7 +1821,7 @@ to speed up repeated connections from the same clients. .. attribute:: SSLContext.sslsocket_class - The return type of :meth:`SSLContext.wrap_sockets`, defaults to + The return type of :meth:`SSLContext.wrap_socket`, defaults to :class:`SSLSocket`. The attribute can be overridden on instance of class in order to return a custom subclass of :class:`SSLSocket`. @@ -1831,7 +1831,7 @@ to speed up repeated connections from the same clients. server_hostname=None, session=None) Wrap the BIO objects *incoming* and *outgoing* and return an instance of - attr:`SSLContext.sslobject_class` (default :class:`SSLObject`). The SSL + :attr:`SSLContext.sslobject_class` (default :class:`SSLObject`). The SSL routines will read input data from the incoming BIO and write data to the outgoing BIO. diff --git a/Doc/library/venv.rst b/Doc/library/venv.rst index 412808a..4f083a3 100644 --- a/Doc/library/venv.rst +++ b/Doc/library/venv.rst @@ -234,14 +234,19 @@ creation according to their needs, the :class:`EnvBuilder` class. There is also a module-level convenience function: .. function:: create(env_dir, system_site_packages=False, clear=False, \ - symlinks=False, with_pip=False) + symlinks=False, with_pip=False, prompt=None) Create an :class:`EnvBuilder` with the given keyword arguments, and call its :meth:`~EnvBuilder.create` method with the *env_dir* argument. + .. versionadded:: 3.3 + .. versionchanged:: 3.4 Added the ``with_pip`` parameter + .. versionchanged:: 3.6 + Added the ``prompt`` parameter + An example of extending ``EnvBuilder`` -------------------------------------- diff --git a/Doc/license.rst b/Doc/license.rst index d3733f5..bf2e4c5 100644 --- a/Doc/license.rst +++ b/Doc/license.rst @@ -561,7 +561,7 @@ SipHash24 --------- The file :file:`Python/pyhash.c` contains Marek Majkowski' implementation of -Dan Bernstein's SipHash24 algorithm. The contains the following note:: +Dan Bernstein's SipHash24 algorithm. It contains the following note:: <MIT License> Copyright (c) 2013 Marek Majkowski <marek@popcount.org> diff --git a/Doc/reference/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst index fb04ccc..13adc1a 100644 --- a/Doc/reference/lexical_analysis.rst +++ b/Doc/reference/lexical_analysis.rst @@ -680,11 +680,12 @@ with a closing curly bracket ``'}'``. Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. -An empty expression is not allowed, and a :keyword:`lambda` expression -must be surrounded by explicit parentheses. Replacement expressions -can contain line breaks (e.g. in triple-quoted strings), but they -cannot contain comments. Each expression is evaluated in the context -where the formatted string literal appears, in order from left to right. +An empty expression is not allowed, and both :keyword:`lambda` and +assignment expressions ``:=`` must be surrounded by explicit parentheses. +Replacement expressions can contain line breaks (e.g. in triple-quoted +strings), but they cannot contain comments. Each expression is evaluated +in the context where the formatted string literal appears, in order from +left to right. If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion ``'!s'`` calls :func:`str` on diff --git a/Doc/tools/templates/download.html b/Doc/tools/templates/download.html index 1a99b18..d9364d6 100644 --- a/Doc/tools/templates/download.html +++ b/Doc/tools/templates/download.html @@ -12,8 +12,7 @@ {% if last_updated %}<p><b>Last updated on: {{ last_updated }}.</b></p>{% endif %} <p>To download an archive containing all the documents for this version of -Python in one of various formats, follow one of links in this table. The numbers -in the table are the size of the download files in megabytes.</p> +Python in one of various formats, follow one of links in this table.</p> <table class="docutils"> <tr><th>Format</th><th>Packed as .zip</th><th>Packed as .tar.bz2</th></tr> diff --git a/Doc/whatsnew/3.8.rst b/Doc/whatsnew/3.8.rst index 64ef6e1..d6388f8 100644 --- a/Doc/whatsnew/3.8.rst +++ b/Doc/whatsnew/3.8.rst @@ -811,6 +811,13 @@ Changes in Python behavior raised when getting the attribute from the type dictionary are no longer ignored. (Contributed by Serhiy Storchaka in :issue:`35459`.) +* Removed ``__str__`` implementations from builtin types :class:`bool`, + :class:`int`, :class:`float`, :class:`complex` and few classes from + the standard library. They now inherit ``__str__()`` from :class:`object`. + As result, defining the ``__repr__()`` method in the subclass of these + classes will affect they string representation. + (Contributed by Serhiy Storchaka in :issue:`36793`.) + * On AIX, :attr:`sys.platform` doesn't contain the major version anymore. It is always ``'aix'``, instead of ``'aix3'`` .. ``'aix7'``. Since older Python versions include the version number, it is recommended to diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py index 44ea5b4..c14d8ca 100644 --- a/Lib/_pydecimal.py +++ b/Lib/_pydecimal.py @@ -5631,8 +5631,6 @@ class _WorkRep(object): def __repr__(self): return "(%r, %r, %r)" % (self.sign, self.int, self.exp) - __str__ = __repr__ - def _normalize(op1, op2, prec = 0): diff --git a/Lib/asyncio/streams.py b/Lib/asyncio/streams.py index 33fc303..c9b1f32 100644 --- a/Lib/asyncio/streams.py +++ b/Lib/asyncio/streams.py @@ -4,6 +4,7 @@ __all__ = ( import socket import sys +import warnings import weakref if hasattr(socket, 'AF_UNIX'): @@ -42,11 +43,14 @@ async def open_connection(host=None, port=None, *, """ if loop is None: loop = events.get_event_loop() - reader = StreamReader(limit=limit, loop=loop) - protocol = StreamReaderProtocol(reader, loop=loop) + reader = StreamReader(limit=limit, loop=loop, + _asyncio_internal=True) + protocol = StreamReaderProtocol(reader, loop=loop, + _asyncio_internal=True) transport, _ = await loop.create_connection( lambda: protocol, host, port, **kwds) - writer = StreamWriter(transport, protocol, reader, loop) + writer = StreamWriter(transport, protocol, reader, loop, + _asyncio_internal=True) return reader, writer @@ -77,9 +81,11 @@ async def start_server(client_connected_cb, host=None, port=None, *, loop = events.get_event_loop() def factory(): - reader = StreamReader(limit=limit, loop=loop) + reader = StreamReader(limit=limit, loop=loop, + _asyncio_internal=True) protocol = StreamReaderProtocol(reader, client_connected_cb, - loop=loop) + loop=loop, + _asyncio_internal=True) return protocol return await loop.create_server(factory, host, port, **kwds) @@ -93,11 +99,14 @@ if hasattr(socket, 'AF_UNIX'): """Similar to `open_connection` but works with UNIX Domain Sockets.""" if loop is None: loop = events.get_event_loop() - reader = StreamReader(limit=limit, loop=loop) - protocol = StreamReaderProtocol(reader, loop=loop) + reader = StreamReader(limit=limit, loop=loop, + _asyncio_internal=True) + protocol = StreamReaderProtocol(reader, loop=loop, + _asyncio_internal=True) transport, _ = await loop.create_unix_connection( lambda: protocol, path, **kwds) - writer = StreamWriter(transport, protocol, reader, loop) + writer = StreamWriter(transport, protocol, reader, loop, + _asyncio_internal=True) return reader, writer async def start_unix_server(client_connected_cb, path=None, *, @@ -107,9 +116,11 @@ if hasattr(socket, 'AF_UNIX'): loop = events.get_event_loop() def factory(): - reader = StreamReader(limit=limit, loop=loop) + reader = StreamReader(limit=limit, loop=loop, + _asyncio_internal=True) protocol = StreamReaderProtocol(reader, client_connected_cb, - loop=loop) + loop=loop, + _asyncio_internal=True) return protocol return await loop.create_unix_server(factory, path, **kwds) @@ -125,11 +136,20 @@ class FlowControlMixin(protocols.Protocol): StreamWriter.drain() must wait for _drain_helper() coroutine. """ - def __init__(self, loop=None): + def __init__(self, loop=None, *, _asyncio_internal=False): if loop is None: self._loop = events.get_event_loop() else: self._loop = loop + if not _asyncio_internal: + # NOTE: + # Avoid inheritance from FlowControlMixin + # Copy-paste the code to your project + # if you need flow control helpers + warnings.warn(f"{self.__class__} should be instaniated " + "by asyncio internals only, " + "please avoid its creation from user code", + DeprecationWarning) self._paused = False self._drain_waiter = None self._connection_lost = False @@ -191,8 +211,9 @@ class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): _source_traceback = None - def __init__(self, stream_reader, client_connected_cb=None, loop=None): - super().__init__(loop=loop) + def __init__(self, stream_reader, client_connected_cb=None, loop=None, + *, _asyncio_internal=False): + super().__init__(loop=loop, _asyncio_internal=_asyncio_internal) if stream_reader is not None: self._stream_reader_wr = weakref.ref(stream_reader, self._on_reader_gc) @@ -253,7 +274,8 @@ class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): if self._client_connected_cb is not None: self._stream_writer = StreamWriter(transport, self, reader, - self._loop) + self._loop, + _asyncio_internal=True) res = self._client_connected_cb(reader, self._stream_writer) if coroutines.iscoroutine(res): @@ -311,7 +333,13 @@ class StreamWriter: directly. """ - def __init__(self, transport, protocol, reader, loop): + def __init__(self, transport, protocol, reader, loop, + *, _asyncio_internal=False): + if not _asyncio_internal: + warnings.warn(f"{self.__class__} should be instaniated " + "by asyncio internals only, " + "please avoid its creation from user code", + DeprecationWarning) self._transport = transport self._protocol = protocol # drain() expects that the reader has an exception() method @@ -388,7 +416,14 @@ class StreamReader: _source_traceback = None - def __init__(self, limit=_DEFAULT_LIMIT, loop=None): + def __init__(self, limit=_DEFAULT_LIMIT, loop=None, + *, _asyncio_internal=False): + if not _asyncio_internal: + warnings.warn(f"{self.__class__} should be instaniated " + "by asyncio internals only, " + "please avoid its creation from user code", + DeprecationWarning) + # The line length limit is a security feature; # it also doubles as half the buffer limit. diff --git a/Lib/asyncio/subprocess.py b/Lib/asyncio/subprocess.py index 90fc00d..fa58e1e 100644 --- a/Lib/asyncio/subprocess.py +++ b/Lib/asyncio/subprocess.py @@ -1,6 +1,7 @@ __all__ = 'create_subprocess_exec', 'create_subprocess_shell' import subprocess +import warnings from . import events from . import protocols @@ -18,8 +19,8 @@ class SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessProtocol): """Like StreamReaderProtocol, but for a subprocess.""" - def __init__(self, limit, loop): - super().__init__(loop=loop) + def __init__(self, limit, loop, *, _asyncio_internal=False): + super().__init__(loop=loop, _asyncio_internal=_asyncio_internal) self._limit = limit self.stdin = self.stdout = self.stderr = None self._transport = None @@ -42,14 +43,16 @@ class SubprocessStreamProtocol(streams.FlowControlMixin, stdout_transport = transport.get_pipe_transport(1) if stdout_transport is not None: self.stdout = streams.StreamReader(limit=self._limit, - loop=self._loop) + loop=self._loop, + _asyncio_internal=True) self.stdout.set_transport(stdout_transport) self._pipe_fds.append(1) stderr_transport = transport.get_pipe_transport(2) if stderr_transport is not None: self.stderr = streams.StreamReader(limit=self._limit, - loop=self._loop) + loop=self._loop, + _asyncio_internal=True) self.stderr.set_transport(stderr_transport) self._pipe_fds.append(2) @@ -58,7 +61,8 @@ class SubprocessStreamProtocol(streams.FlowControlMixin, self.stdin = streams.StreamWriter(stdin_transport, protocol=self, reader=None, - loop=self._loop) + loop=self._loop, + _asyncio_internal=True) def pipe_data_received(self, fd, data): if fd == 1: @@ -104,7 +108,13 @@ class SubprocessStreamProtocol(streams.FlowControlMixin, class Process: - def __init__(self, transport, protocol, loop): + def __init__(self, transport, protocol, loop, *, _asyncio_internal=False): + if not _asyncio_internal: + warnings.warn(f"{self.__class__} should be instaniated " + "by asyncio internals only, " + "please avoid its creation from user code", + DeprecationWarning) + self._transport = transport self._protocol = protocol self._loop = loop @@ -195,12 +205,13 @@ async def create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, if loop is None: loop = events.get_event_loop() protocol_factory = lambda: SubprocessStreamProtocol(limit=limit, - loop=loop) + loop=loop, + _asyncio_internal=True) transport, protocol = await loop.subprocess_shell( protocol_factory, cmd, stdin=stdin, stdout=stdout, stderr=stderr, **kwds) - return Process(transport, protocol, loop) + return Process(transport, protocol, loop, _asyncio_internal=True) async def create_subprocess_exec(program, *args, stdin=None, stdout=None, @@ -209,10 +220,11 @@ async def create_subprocess_exec(program, *args, stdin=None, stdout=None, if loop is None: loop = events.get_event_loop() protocol_factory = lambda: SubprocessStreamProtocol(limit=limit, - loop=loop) + loop=loop, + _asyncio_internal=True) transport, protocol = await loop.subprocess_exec( protocol_factory, program, *args, stdin=stdin, stdout=stdout, stderr=stderr, **kwds) - return Process(transport, protocol, loop) + return Process(transport, protocol, loop, _asyncio_internal=True) diff --git a/Lib/asyncore.py b/Lib/asyncore.py index 828f4d4..0e92be3 100644 --- a/Lib/asyncore.py +++ b/Lib/asyncore.py @@ -262,8 +262,6 @@ class dispatcher: status.append(repr(self.addr)) return '<%s at %#x>' % (' '.join(status), id(self)) - __str__ = __repr__ - def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: @@ -649,6 +649,7 @@ class Bdb: self.quitting = True sys.settrace(None) return res + runcall.__text_signature__ = '($self, func, /, *args, **kwds)' def set_trace(): diff --git a/Lib/cProfile.py b/Lib/cProfile.py index 2e449cc..369d02e 100755 --- a/Lib/cProfile.py +++ b/Lib/cProfile.py @@ -124,6 +124,7 @@ class Profile(_lsprof.Profiler): return func(*args, **kw) finally: self.disable() + runcall.__text_signature__ = '($self, func, /, *args, **kw)' def __enter__(self): self.enable() diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index 9657c1c..e6cafb3 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -1018,6 +1018,8 @@ class UserDict(_collections_abc.MutableMapping): self.update(dict) if kwargs: self.update(kwargs) + __init__.__text_signature__ = '($self, dict=None, /, **kwargs)' + def __len__(self): return len(self.data) def __getitem__(self, key): if key in self.data: diff --git a/Lib/concurrent/futures/_base.py b/Lib/concurrent/futures/_base.py index ea16eef..8f155f0 100644 --- a/Lib/concurrent/futures/_base.py +++ b/Lib/concurrent/futures/_base.py @@ -567,6 +567,7 @@ class Executor(object): 'got %d' % (len(args)-1)) raise NotImplementedError() + submit.__text_signature__ = '($self, fn, /, *args, **kwargs)' def map(self, fn, *iterables, timeout=None, chunksize=1): """Returns an iterator equivalent to map(fn, iter). diff --git a/Lib/concurrent/futures/process.py b/Lib/concurrent/futures/process.py index e6ce278..21bf4a4 100644 --- a/Lib/concurrent/futures/process.py +++ b/Lib/concurrent/futures/process.py @@ -630,6 +630,7 @@ class ProcessPoolExecutor(_base.Executor): self._start_queue_management_thread() return f + submit.__text_signature__ = _base.Executor.submit.__text_signature__ submit.__doc__ = _base.Executor.submit.__doc__ def map(self, fn, *iterables, timeout=None, chunksize=1): diff --git a/Lib/concurrent/futures/thread.py b/Lib/concurrent/futures/thread.py index 0a61e3a..2af31a1 100644 --- a/Lib/concurrent/futures/thread.py +++ b/Lib/concurrent/futures/thread.py @@ -174,6 +174,7 @@ class ThreadPoolExecutor(_base.Executor): self._work_queue.put(w) self._adjust_thread_count() return f + submit.__text_signature__ = _base.Executor.submit.__text_signature__ submit.__doc__ = _base.Executor.submit.__doc__ def _adjust_thread_count(self): diff --git a/Lib/contextlib.py b/Lib/contextlib.py index ae498a2..de989a0 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -454,6 +454,7 @@ class _BaseExitStack: _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper) return callback # Allow use as a decorator + callback.__text_signature__ = '($self, callback, /, *args, **kwds)' def _push_cm_exit(self, cm, cm_exit): """Helper to correctly register callbacks to __exit__ methods.""" @@ -615,6 +616,7 @@ class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager): _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper, False) return callback # Allow use as a decorator + push_async_callback.__text_signature__ = '($self, callback, /, *args, **kwds)' async def aclose(self): """Immediately unwind the context stack.""" diff --git a/Lib/curses/__init__.py b/Lib/curses/__init__.py index 44a1984..24ff3ca 100644 --- a/Lib/curses/__init__.py +++ b/Lib/curses/__init__.py @@ -110,3 +110,4 @@ def wrapper(*args, **kwds): echo() nocbreak() endwin() +wrapper.__text_signature__ = '(func, /, *args, **kwds)' diff --git a/Lib/doctest.py b/Lib/doctest.py index 79d91a0..bf4889f 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -2300,7 +2300,7 @@ class DocTestCase(unittest.TestCase): name = self._dt_test.name.split('.') return "%s (%s)" % (name[-1], '.'.join(name[:-1])) - __str__ = __repr__ + __str__ = object.__str__ def shortDescription(self): return "Doctest: " + self._dt_test.name @@ -2399,7 +2399,6 @@ class DocFileCase(DocTestCase): def __repr__(self): return self._dt_test.filename - __str__ = __repr__ def format_failure(self, err): return ('Failed doctest test for %s\n File "%s", line 0\n\n%s' diff --git a/Lib/email/charset.py b/Lib/email/charset.py index ee56404..d3d759a 100644 --- a/Lib/email/charset.py +++ b/Lib/email/charset.py @@ -241,11 +241,9 @@ class Charset: self.output_codec = CODEC_MAP.get(self.output_charset, self.output_charset) - def __str__(self): + def __repr__(self): return self.input_charset.lower() - __repr__ = __str__ - def __eq__(self, other): return str(self) == str(other).lower() diff --git a/Lib/functools.py b/Lib/functools.py index 1f1874d..28d9f6f 100644 --- a/Lib/functools.py +++ b/Lib/functools.py @@ -388,6 +388,7 @@ class partialmethod(object): self.func = func self.args = args self.keywords = keywords + __init__.__text_signature__ = '($self, func, /, *args, **keywords)' def __repr__(self): args = ", ".join(map(repr, self.args)) diff --git a/Lib/http/client.py b/Lib/http/client.py index f71a062..82908eb 100644 --- a/Lib/http/client.py +++ b/Lib/http/client.py @@ -1419,8 +1419,7 @@ class IncompleteRead(HTTPException): e = '' return '%s(%i bytes read%s)' % (self.__class__.__name__, len(self.partial), e) - def __str__(self): - return repr(self) + __str__ = object.__str__ class ImproperConnectionState(HTTPException): pass diff --git a/Lib/idlelib/configdialog.py b/Lib/idlelib/configdialog.py index 31520a3..4aaec13 100644 --- a/Lib/idlelib/configdialog.py +++ b/Lib/idlelib/configdialog.py @@ -2225,7 +2225,7 @@ key set, with a different name. 'General': ''' General: -AutoComplete: Popupwait is milleseconds to wait after key char, without +AutoComplete: Popupwait is milliseconds to wait after key char, without cursor movement, before popping up completion box. Key char is '.' after identifier or a '/' (or '\\' on Windows) within a string. diff --git a/Lib/idlelib/help.html b/Lib/idlelib/help.html index 7e743e6..ba44331 100644 --- a/Lib/idlelib/help.html +++ b/Lib/idlelib/help.html @@ -721,7 +721,7 @@ facilitate development of tkinter programs. Enter <code class="docutils literal <span class="pre">root</span> <span class="pre">=</span> <span class="pre">tk.Tk()</span></code> in standard Python and nothing appears. Enter the same in IDLE and a tk window appears. In standard Python, one must also enter <code class="docutils literal notranslate"><span class="pre">root.update()</span></code> to see the window. IDLE does the equivalent in the -background, about 20 times a second, which is about every 50 milleseconds. +background, about 20 times a second, which is about every 50 milliseconds. Next enter <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">=</span> <span class="pre">tk.Button(root,</span> <span class="pre">text='button');</span> <span class="pre">b.pack()</span></code>. Again, nothing visibly changes in standard Python until one enters <code class="docutils literal notranslate"><span class="pre">root.update()</span></code>.</p> <p>Most tkinter programs run <code class="docutils literal notranslate"><span class="pre">root.mainloop()</span></code>, which usually does not diff --git a/Lib/idlelib/help.py b/Lib/idlelib/help.py index 0603ede..652444a 100644 --- a/Lib/idlelib/help.py +++ b/Lib/idlelib/help.py @@ -2,7 +2,7 @@ Contents are subject to revision at any time, without notice. -Help => About IDLE: diplay About Idle dialog +Help => About IDLE: display About Idle dialog <to be moved here from help_about.py> diff --git a/Lib/idlelib/idle_test/test_config.py b/Lib/idlelib/idle_test/test_config.py index 7e2c1fd..255210d 100644 --- a/Lib/idlelib/idle_test/test_config.py +++ b/Lib/idlelib/idle_test/test_config.py @@ -521,7 +521,7 @@ class IdleConfTest(unittest.TestCase): def test_get_keyset(self): conf = self.mock_config() - # Conflic with key set, should be disable to '' + # Conflict with key set, should be disable to '' conf.defaultCfg['extensions'].add_section('Foobar') conf.defaultCfg['extensions'].add_section('Foobar_cfgBindings') conf.defaultCfg['extensions'].set('Foobar', 'enable', 'True') diff --git a/Lib/inspect.py b/Lib/inspect.py index c460309..6c30279 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -2121,7 +2121,7 @@ def _signature_from_builtin(cls, func, skip_bound_arg=True): return _signature_fromstr(cls, func, s, skip_bound_arg) -def _signature_from_function(cls, func): +def _signature_from_function(cls, func, skip_bound_arg=True): """Private helper: constructs Signature for the given python function.""" is_duck_function = False @@ -2133,6 +2133,10 @@ def _signature_from_function(cls, func): # of pure function: raise TypeError('{!r} is not a Python function'.format(func)) + s = getattr(func, "__text_signature__", None) + if s: + return _signature_fromstr(cls, func, s, skip_bound_arg) + Parameter = cls._parameter_cls # Parameter information. @@ -2301,7 +2305,8 @@ def _signature_from_callable(obj, *, if isfunction(obj) or _signature_is_functionlike(obj): # If it's a pure Python function, or an object that is duck type # of a Python function (Cython functions, for instance), then: - return _signature_from_function(sigcls, obj) + return _signature_from_function(sigcls, obj, + skip_bound_arg=skip_bound_arg) if _signature_is_builtin(obj): return _signature_from_builtin(sigcls, obj, diff --git a/Lib/json/encoder.py b/Lib/json/encoder.py index 2d7b898..c8c78b9 100644 --- a/Lib/json/encoder.py +++ b/Lib/json/encoder.py @@ -268,7 +268,7 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, list=list, str=str, tuple=tuple, - _intstr=int.__str__, + _intstr=int.__repr__, ): if _indent is not None and not isinstance(_indent, str): @@ -307,7 +307,7 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, elif value is False: yield buf + 'false' elif isinstance(value, int): - # Subclasses of int/float may override __str__, but we still + # Subclasses of int/float may override __repr__, but we still # want to encode them as integers/floats in JSON. One example # within the standard library is IntEnum. yield buf + _intstr(value) diff --git a/Lib/lib2to3/pgen2/tokenize.py b/Lib/lib2to3/pgen2/tokenize.py index c07b34f..279d322 100644 --- a/Lib/lib2to3/pgen2/tokenize.py +++ b/Lib/lib2to3/pgen2/tokenize.py @@ -321,7 +321,7 @@ def untokenize(iterable): Round-trip invariant for full input: Untokenized source will match input source exactly - Round-trip invariant for limited intput: + Round-trip invariant for limited input: # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py index 7355396..e093982 100644 --- a/Lib/logging/__init__.py +++ b/Lib/logging/__init__.py @@ -364,12 +364,10 @@ class LogRecord(object): else: self.process = None - def __str__(self): + def __repr__(self): return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno, self.pathname, self.lineno, self.msg) - __repr__ = __str__ - def getMessage(self): """ Return the message for this LogRecord. diff --git a/Lib/multiprocessing/managers.py b/Lib/multiprocessing/managers.py index 80c3ddb..22abd47 100644 --- a/Lib/multiprocessing/managers.py +++ b/Lib/multiprocessing/managers.py @@ -419,6 +419,7 @@ class Server(object): self.incref(c, ident) return ident, tuple(exposed) + create.__text_signature__ = '($self, c, typeid, /, *args, **kwds)' def get_methods(self, c, token): ''' @@ -1309,6 +1310,7 @@ if HAS_SHMEM: if hasattr(self.registry[typeid][-1], "_shared_memory_proxy"): kwargs['shared_memory_context'] = self.shared_memory_context return Server.create(*args, **kwargs) + create.__text_signature__ = '($self, c, typeid, /, *args, **kwargs)' def shutdown(self, c): "Call unlink() on all tracked shared memory, terminate the Server." diff --git a/Lib/multiprocessing/resource_sharer.py b/Lib/multiprocessing/resource_sharer.py index 730b2aa..8d5c990 100644 --- a/Lib/multiprocessing/resource_sharer.py +++ b/Lib/multiprocessing/resource_sharer.py @@ -59,7 +59,7 @@ else: class _ResourceSharer(object): - '''Manager for resouces using background thread.''' + '''Manager for resources using background thread.''' def __init__(self): self._key = 0 self._cache = {} diff --git a/Lib/pathlib.py b/Lib/pathlib.py index 1ba98b1..952cd94 100644 --- a/Lib/pathlib.py +++ b/Lib/pathlib.py @@ -34,7 +34,7 @@ __all__ = [ # Internals # -# EBADF - guard agains macOS `stat` throwing EBADF +# EBADF - guard against macOS `stat` throwing EBADF _IGNORED_ERROS = (ENOENT, ENOTDIR, EBADF) _IGNORED_WINERRORS = ( diff --git a/Lib/platform.py b/Lib/platform.py index 9f7bd95..6fbb7b0 100755 --- a/Lib/platform.py +++ b/Lib/platform.py @@ -72,7 +72,7 @@ # type information # 0.4.0 - added win32_ver() and modified the platform() output for WinXX # 0.3.4 - fixed a bug in _follow_symlinks() -# 0.3.3 - fixed popen() and "file" command invokation bugs +# 0.3.3 - fixed popen() and "file" command invocation bugs # 0.3.2 - added architecture() API and support for it in platform() # 0.3.1 - fixed syscmd_ver() RE to support Windows NT # 0.3.0 - added system alias support diff --git a/Lib/profile.py b/Lib/profile.py index 9a865d3..1346297 100755 --- a/Lib/profile.py +++ b/Lib/profile.py @@ -447,6 +447,7 @@ class Profile: return func(*args, **kw) finally: sys.setprofile(None) + runcall.__text_signature__ = '($self, func, /, *args, **kw)' #****************************************************************** diff --git a/Lib/pstats.py b/Lib/pstats.py index ded5ae5..b7649eb 100644 --- a/Lib/pstats.py +++ b/Lib/pstats.py @@ -509,7 +509,7 @@ def func_std_string(func_name): # match what old profile produced return "%s:%d(%s)" % func_name #************************************************************************** -# The following functions combine statists for pairs functions. +# The following functions combine statistics for pairs functions. # The bulk of the processing involves correctly handling "call" lists, # such as callers and callees. #************************************************************************** diff --git a/Lib/sre_constants.py b/Lib/sre_constants.py index 13deb00..8e613cb 100644 --- a/Lib/sre_constants.py +++ b/Lib/sre_constants.py @@ -59,11 +59,9 @@ class _NamedIntConstant(int): self.name = name return self - def __str__(self): + def __repr__(self): return self.name - __repr__ = __str__ - MAXREPEAT = _NamedIntConstant(MAXREPEAT, 'MAXREPEAT') def _makecodes(names): diff --git a/Lib/subprocess.py b/Lib/subprocess.py index 0496b44..6cc9eb3 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -203,7 +203,6 @@ if _mswindows: return "%s(%d)" % (self.__class__.__name__, int(self)) __del__ = Close - __str__ = __repr__ else: # When select or poll has indicated that the file is writable, # we can write up to _PIPE_BUF bytes without risk of blocking. diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py index 9fe32eb..af0047f 100644 --- a/Lib/test/datetimetester.py +++ b/Lib/test/datetimetester.py @@ -3483,7 +3483,7 @@ class TZInfoBase: self.assertEqual(got, expected) # However, if they're different members, uctoffset is not ignored. - # Note that a time can't actually have an operand-depedent offset, + # Note that a time can't actually have an operand-dependent offset, # though (and time.utcoffset() passes None to tzinfo.utcoffset()), # so skip this test for time. if cls is not time: diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py index 8f687c4..bb8e6ce 100644 --- a/Lib/test/pickletester.py +++ b/Lib/test/pickletester.py @@ -2222,7 +2222,7 @@ class AbstractPickleTests(unittest.TestCase): frame_size = self.FRAME_SIZE_TARGET num_frames = 20 - # Large byte objects (dict values) intermitted with small objects + # Large byte objects (dict values) intermittent with small objects # (dict keys) obj = {i: bytes([i]) * frame_size for i in range(num_frames)} diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py index dc96318..9e60d96 100644 --- a/Lib/test/support/__init__.py +++ b/Lib/test/support/__init__.py @@ -1006,7 +1006,7 @@ def temp_dir(path=None, quiet=False): yield path finally: # In case the process forks, let only the parent remove the - # directory. The child has a diffent process id. (bpo-30028) + # directory. The child has a different process id. (bpo-30028) if dir_created and pid == os.getpid(): rmtree(path) diff --git a/Lib/test/test_asyncio/test_streams.py b/Lib/test/test_asyncio/test_streams.py index 630f91d..c1cc9d7 100644 --- a/Lib/test/test_asyncio/test_streams.py +++ b/Lib/test/test_asyncio/test_streams.py @@ -42,7 +42,7 @@ class StreamTests(test_utils.TestCase): @mock.patch('asyncio.streams.events') def test_ctor_global_loop(self, m_events): - stream = asyncio.StreamReader() + stream = asyncio.StreamReader(_asyncio_internal=True) self.assertIs(stream._loop, m_events.get_event_loop.return_value) def _basetest_open_connection(self, open_connection_fut): @@ -135,20 +135,23 @@ class StreamTests(test_utils.TestCase): self._basetest_open_connection_error(conn_fut) def test_feed_empty_data(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'') self.assertEqual(b'', stream._buffer) def test_feed_nonempty_data(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(self.DATA) self.assertEqual(self.DATA, stream._buffer) def test_read_zero(self): # Read zero bytes. - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(self.DATA) data = self.loop.run_until_complete(stream.read(0)) @@ -157,7 +160,8 @@ class StreamTests(test_utils.TestCase): def test_read(self): # Read bytes. - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) read_task = asyncio.Task(stream.read(30), loop=self.loop) def cb(): @@ -170,7 +174,8 @@ class StreamTests(test_utils.TestCase): def test_read_line_breaks(self): # Read bytes without line breaks. - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'line1') stream.feed_data(b'line2') @@ -181,7 +186,8 @@ class StreamTests(test_utils.TestCase): def test_read_eof(self): # Read bytes, stop at eof. - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) read_task = asyncio.Task(stream.read(1024), loop=self.loop) def cb(): @@ -194,7 +200,8 @@ class StreamTests(test_utils.TestCase): def test_read_until_eof(self): # Read all bytes until eof. - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) read_task = asyncio.Task(stream.read(-1), loop=self.loop) def cb(): @@ -209,7 +216,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'', stream._buffer) def test_read_exception(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'line\n') data = self.loop.run_until_complete(stream.read(2)) @@ -221,13 +229,16 @@ class StreamTests(test_utils.TestCase): def test_invalid_limit(self): with self.assertRaisesRegex(ValueError, 'imit'): - asyncio.StreamReader(limit=0, loop=self.loop) + asyncio.StreamReader(limit=0, loop=self.loop, + _asyncio_internal=True) with self.assertRaisesRegex(ValueError, 'imit'): - asyncio.StreamReader(limit=-1, loop=self.loop) + asyncio.StreamReader(limit=-1, loop=self.loop, + _asyncio_internal=True) def test_read_limit(self): - stream = asyncio.StreamReader(limit=3, loop=self.loop) + stream = asyncio.StreamReader(limit=3, loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'chunk') data = self.loop.run_until_complete(stream.read(5)) self.assertEqual(b'chunk', data) @@ -236,7 +247,8 @@ class StreamTests(test_utils.TestCase): def test_readline(self): # Read one line. 'readline' will need to wait for the data # to come from 'cb' - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'chunk1 ') read_task = asyncio.Task(stream.readline(), loop=self.loop) @@ -254,7 +266,8 @@ class StreamTests(test_utils.TestCase): # Read one line. The data is in StreamReader's buffer # before the event loop is run. - stream = asyncio.StreamReader(limit=3, loop=self.loop) + stream = asyncio.StreamReader(limit=3, loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'li') stream.feed_data(b'ne1\nline2\n') @@ -263,7 +276,8 @@ class StreamTests(test_utils.TestCase): # The buffer should contain the remaining data after exception self.assertEqual(b'line2\n', stream._buffer) - stream = asyncio.StreamReader(limit=3, loop=self.loop) + stream = asyncio.StreamReader(limit=3, loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'li') stream.feed_data(b'ne1') stream.feed_data(b'li') @@ -278,7 +292,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'', stream._buffer) def test_at_eof(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) self.assertFalse(stream.at_eof()) stream.feed_data(b'some data\n') @@ -296,7 +311,8 @@ class StreamTests(test_utils.TestCase): # Read one line. StreamReaders are fed with data after # their 'readline' methods are called. - stream = asyncio.StreamReader(limit=7, loop=self.loop) + stream = asyncio.StreamReader(limit=7, loop=self.loop, + _asyncio_internal=True) def cb(): stream.feed_data(b'chunk1') stream.feed_data(b'chunk2') @@ -310,7 +326,8 @@ class StreamTests(test_utils.TestCase): # a ValueError it should be empty. self.assertEqual(b'', stream._buffer) - stream = asyncio.StreamReader(limit=7, loop=self.loop) + stream = asyncio.StreamReader(limit=7, loop=self.loop, + _asyncio_internal=True) def cb(): stream.feed_data(b'chunk1') stream.feed_data(b'chunk2\n') @@ -323,7 +340,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'chunk3\n', stream._buffer) # check strictness of the limit - stream = asyncio.StreamReader(limit=7, loop=self.loop) + stream = asyncio.StreamReader(limit=7, loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'1234567\n') line = self.loop.run_until_complete(stream.readline()) self.assertEqual(b'1234567\n', line) @@ -342,7 +360,8 @@ class StreamTests(test_utils.TestCase): def test_readline_nolimit_nowait(self): # All needed data for the first 'readline' call will be # in the buffer. - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(self.DATA[:6]) stream.feed_data(self.DATA[6:]) @@ -352,7 +371,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'line2\nline3\n', stream._buffer) def test_readline_eof(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'some data') stream.feed_eof() @@ -360,14 +380,16 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'some data', line) def test_readline_empty_eof(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_eof() line = self.loop.run_until_complete(stream.readline()) self.assertEqual(b'', line) def test_readline_read_byte_count(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(self.DATA) self.loop.run_until_complete(stream.readline()) @@ -378,7 +400,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'ine3\n', stream._buffer) def test_readline_exception(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'line\n') data = self.loop.run_until_complete(stream.readline()) @@ -390,12 +413,14 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'', stream._buffer) def test_readuntil_separator(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) with self.assertRaisesRegex(ValueError, 'Separator should be'): self.loop.run_until_complete(stream.readuntil(separator=b'')) def test_readuntil_multi_chunks(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'lineAAA') data = self.loop.run_until_complete(stream.readuntil(separator=b'AAA')) @@ -413,7 +438,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'xxx', stream._buffer) def test_readuntil_multi_chunks_1(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'QWEaa') stream.feed_data(b'XYaa') @@ -448,7 +474,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'', stream._buffer) def test_readuntil_eof(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'some dataAA') stream.feed_eof() @@ -459,7 +486,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'', stream._buffer) def test_readuntil_limit_found_sep(self): - stream = asyncio.StreamReader(loop=self.loop, limit=3) + stream = asyncio.StreamReader(loop=self.loop, limit=3, + _asyncio_internal=True) stream.feed_data(b'some dataAA') with self.assertRaisesRegex(asyncio.LimitOverrunError, @@ -477,7 +505,8 @@ class StreamTests(test_utils.TestCase): def test_readexactly_zero_or_less(self): # Read exact number of bytes (zero or less). - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(self.DATA) data = self.loop.run_until_complete(stream.readexactly(0)) @@ -490,7 +519,8 @@ class StreamTests(test_utils.TestCase): def test_readexactly(self): # Read exact number of bytes. - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) n = 2 * len(self.DATA) read_task = asyncio.Task(stream.readexactly(n), loop=self.loop) @@ -506,7 +536,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(self.DATA, stream._buffer) def test_readexactly_limit(self): - stream = asyncio.StreamReader(limit=3, loop=self.loop) + stream = asyncio.StreamReader(limit=3, loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'chunk') data = self.loop.run_until_complete(stream.readexactly(5)) self.assertEqual(b'chunk', data) @@ -514,7 +545,8 @@ class StreamTests(test_utils.TestCase): def test_readexactly_eof(self): # Read exact number of bytes (eof). - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) n = 2 * len(self.DATA) read_task = asyncio.Task(stream.readexactly(n), loop=self.loop) @@ -532,7 +564,8 @@ class StreamTests(test_utils.TestCase): self.assertEqual(b'', stream._buffer) def test_readexactly_exception(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'line\n') data = self.loop.run_until_complete(stream.readexactly(2)) @@ -543,7 +576,8 @@ class StreamTests(test_utils.TestCase): ValueError, self.loop.run_until_complete, stream.readexactly(2)) def test_exception(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) self.assertIsNone(stream.exception()) exc = ValueError() @@ -551,7 +585,8 @@ class StreamTests(test_utils.TestCase): self.assertIs(stream.exception(), exc) def test_exception_waiter(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) @asyncio.coroutine def set_err(): @@ -565,7 +600,8 @@ class StreamTests(test_utils.TestCase): self.assertRaises(ValueError, t1.result) def test_exception_cancel(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) t = asyncio.Task(stream.readline(), loop=self.loop) test_utils.run_briefly(self.loop) @@ -742,8 +778,10 @@ os.close(fd) args = [sys.executable, '-c', code, str(wfd)] pipe = open(rfd, 'rb', 0) - reader = asyncio.StreamReader(loop=self.loop, limit=1) - protocol = asyncio.StreamReaderProtocol(reader, loop=self.loop) + reader = asyncio.StreamReader(loop=self.loop, limit=1, + _asyncio_internal=True) + protocol = asyncio.StreamReaderProtocol(reader, loop=self.loop, + _asyncio_internal=True) transport, _ = self.loop.run_until_complete( self.loop.connect_read_pipe(lambda: protocol, pipe)) @@ -769,7 +807,7 @@ os.close(fd) # asyncio issue #184: Ensure that StreamReaderProtocol constructor # retrieves the current loop if the loop parameter is not set - reader = asyncio.StreamReader() + reader = asyncio.StreamReader(_asyncio_internal=True) self.assertIs(reader._loop, self.loop) def test_streamreaderprotocol_constructor(self): @@ -779,7 +817,7 @@ os.close(fd) # asyncio issue #184: Ensure that StreamReaderProtocol constructor # retrieves the current loop if the loop parameter is not set reader = mock.Mock() - protocol = asyncio.StreamReaderProtocol(reader) + protocol = asyncio.StreamReaderProtocol(reader, _asyncio_internal=True) self.assertIs(protocol._loop, self.loop) def test_drain_raises(self): @@ -824,32 +862,38 @@ os.close(fd) thread.join() def test___repr__(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) self.assertEqual("<StreamReader>", repr(stream)) def test___repr__nondefault_limit(self): - stream = asyncio.StreamReader(loop=self.loop, limit=123) + stream = asyncio.StreamReader(loop=self.loop, limit=123, + _asyncio_internal=True) self.assertEqual("<StreamReader limit=123>", repr(stream)) def test___repr__eof(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_eof() self.assertEqual("<StreamReader eof>", repr(stream)) def test___repr__data(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream.feed_data(b'data') self.assertEqual("<StreamReader 4 bytes>", repr(stream)) def test___repr__exception(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) exc = RuntimeError() stream.set_exception(exc) self.assertEqual("<StreamReader exception=RuntimeError()>", repr(stream)) def test___repr__waiter(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream._waiter = asyncio.Future(loop=self.loop) self.assertRegex( repr(stream), @@ -860,7 +904,8 @@ os.close(fd) self.assertEqual("<StreamReader>", repr(stream)) def test___repr__transport(self): - stream = asyncio.StreamReader(loop=self.loop) + stream = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) stream._transport = mock.Mock() stream._transport.__repr__ = mock.Mock() stream._transport.__repr__.return_value = "<Transport>" @@ -947,8 +992,10 @@ os.close(fd) self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx)) with test_utils.run_test_server() as httpd: - rd = asyncio.StreamReader(loop=self.loop) - pr = asyncio.StreamReaderProtocol(rd, loop=self.loop) + rd = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) + pr = asyncio.StreamReaderProtocol(rd, loop=self.loop, + _asyncio_internal=True) del rd gc.collect() tr, _ = self.loop.run_until_complete( @@ -1005,6 +1052,25 @@ os.close(fd) self.assertEqual(messages, []) + def test_stream_reader_create_warning(self): + with self.assertWarns(DeprecationWarning): + asyncio.StreamReader(loop=self.loop) + + def test_stream_reader_protocol_create_warning(self): + reader = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) + with self.assertWarns(DeprecationWarning): + asyncio.StreamReaderProtocol(reader, loop=self.loop) + + def test_stream_writer_create_warning(self): + reader = asyncio.StreamReader(loop=self.loop, + _asyncio_internal=True) + proto = asyncio.StreamReaderProtocol(reader, loop=self.loop, + _asyncio_internal=True) + with self.assertWarns(DeprecationWarning): + asyncio.StreamWriter('transport', proto, reader, self.loop) + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_asyncio/test_subprocess.py b/Lib/test/test_asyncio/test_subprocess.py index a5bdb8e..3908aab 100644 --- a/Lib/test/test_asyncio/test_subprocess.py +++ b/Lib/test/test_asyncio/test_subprocess.py @@ -510,6 +510,18 @@ class SubprocessMixin: self.loop.run_until_complete(execute()) + def test_subprocess_protocol_create_warning(self): + with self.assertWarns(DeprecationWarning): + subprocess.SubprocessStreamProtocol(limit=10, loop=self.loop) + + def test_process_create_warning(self): + proto = subprocess.SubprocessStreamProtocol(limit=10, loop=self.loop, + _asyncio_internal=True) + transp = mock.Mock() + + with self.assertWarns(DeprecationWarning): + subprocess.Process(transp, proto, loop=self.loop) + if sys.platform != 'win32': # Unix diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py index d320a96..8672106 100755 --- a/Lib/test/test_dataclasses.py +++ b/Lib/test/test_dataclasses.py @@ -1458,7 +1458,7 @@ class TestCase(unittest.TestCase): } ) - # Make sure that the returned dicts are actuall OrderedDicts. + # Make sure that the returned dicts are actually OrderedDicts. self.assertIs(type(d), OrderedDict) self.assertIs(type(d['y'][1]), OrderedDict) diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py index 6591461..968cbd8 100644 --- a/Lib/test/test_httplib.py +++ b/Lib/test/test_httplib.py @@ -4,6 +4,7 @@ import io import itertools import os import array +import re import socket import threading @@ -1619,14 +1620,30 @@ class HTTPSTest(TestCase): # We feed the server's cert as a validating cert import ssl support.requires('network') - with support.transient_internet('self-signed.pythontest.net'): + selfsigned_pythontestdotnet = 'self-signed.pythontest.net' + with support.transient_internet(selfsigned_pythontestdotnet): context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED) self.assertEqual(context.check_hostname, True) context.load_verify_locations(CERT_selfsigned_pythontestdotnet) - h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context) - h.request('GET', '/') - resp = h.getresponse() + try: + h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443, + context=context) + h.request('GET', '/') + resp = h.getresponse() + except ssl.SSLError as ssl_err: + ssl_err_str = str(ssl_err) + # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on + # modern Linux distros (Debian Buster, etc) default OpenSSL + # configurations it'll fail saying "key too weak" until we + # address https://bugs.python.org/issue36816 to use a proper + # key size on self-signed.pythontest.net. + if re.search(r'(?i)key.too.weak', ssl_err_str): + raise unittest.SkipTest( + f'Got {ssl_err_str} trying to connect ' + f'to {selfsigned_pythontestdotnet}. ' + 'See https://bugs.python.org/issue36816.') + raise server_string = resp.getheader('server') resp.close() h.close() diff --git a/Lib/test/test_importlib/test_lazy.py b/Lib/test/test_importlib/test_lazy.py index ffd8dc6..28608e9 100644 --- a/Lib/test/test_importlib/test_lazy.py +++ b/Lib/test/test_importlib/test_lazy.py @@ -56,7 +56,7 @@ class LazyLoaderTests(unittest.TestCase): def test_init(self): with self.assertRaises(TypeError): - # Classes that dono't define exec_module() trigger TypeError. + # Classes that don't define exec_module() trigger TypeError. util.LazyLoader(object) def new_module(self, source_code=None): diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 3c825b0..c54cdb2 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -3782,6 +3782,17 @@ class TestSignatureDefinitions(unittest.TestCase): with self.subTest(builtin=name): self.assertIsNone(obj.__text_signature__) + def test_python_function_override_signature(self): + def func(*args, **kwargs): + pass + func.__text_signature__ = '($self, a, b=1, *args, c, d=2, **kwargs)' + sig = inspect.signature(func) + self.assertIsNotNone(sig) + self.assertEqual(str(sig), '(self, /, a, b=1, *args, c, d=2, **kwargs)') + func.__text_signature__ = '($self, a, b=1, /, *args, c, d=2, **kwargs)' + sig = inspect.signature(func) + self.assertEqual(str(sig), '(self, a, b=1, /, *args, c, d=2, **kwargs)') + class NTimesUnwrappable: def __init__(self, n): diff --git a/Lib/test/test_nntplib.py b/Lib/test/test_nntplib.py index 8c1032b..618b403 100644 --- a/Lib/test/test_nntplib.py +++ b/Lib/test/test_nntplib.py @@ -6,6 +6,7 @@ import unittest import functools import contextlib import os.path +import re import threading from test import support @@ -21,6 +22,13 @@ except ImportError: TIMEOUT = 30 certfile = os.path.join(os.path.dirname(__file__), 'keycert3.pem') +if ssl is not None: + SSLError = ssl.SSLError +else: + class SSLError(Exception): + """Non-existent exception class when we lack SSL support.""" + reason = "This will never be raised." + # TODO: # - test the `file` arg to more commands # - test error conditions @@ -261,14 +269,21 @@ class NetworkedNNTPTestsMixin: return False return True - with self.NNTP_CLASS(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) as server: - self.assertTrue(is_connected()) - self.assertTrue(server.help()) - self.assertFalse(is_connected()) - - with self.NNTP_CLASS(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) as server: - server.quit() - self.assertFalse(is_connected()) + try: + with self.NNTP_CLASS(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) as server: + self.assertTrue(is_connected()) + self.assertTrue(server.help()) + self.assertFalse(is_connected()) + + with self.NNTP_CLASS(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) as server: + server.quit() + self.assertFalse(is_connected()) + except SSLError as ssl_err: + # matches "[SSL: DH_KEY_TOO_SMALL] dh key too small" + if re.search(r'(?i)KEY.TOO.SMALL', ssl_err.reason): + raise unittest.SkipTest(f"Got {ssl_err} connecting " + f"to {self.NNTP_HOST!r}") + raise NetworkedNNTPTestsMixin.wrap_methods() @@ -294,6 +309,12 @@ class NetworkedNNTPTests(NetworkedNNTPTestsMixin, unittest.TestCase): try: cls.server = cls.NNTP_CLASS(cls.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) + except SSLError as ssl_err: + # matches "[SSL: DH_KEY_TOO_SMALL] dh key too small" + if re.search(r'(?i)KEY.TOO.SMALL', ssl_err.reason): + raise unittest.SkipTest(f"{cls} got {ssl_err} connecting " + f"to {cls.NNTP_HOST!r}") + raise except EOF_ERRORS: raise unittest.SkipTest(f"{cls} got EOF error on connecting " f"to {cls.NNTP_HOST!r}") diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index e818a7b..ff1ddca 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -719,7 +719,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase): c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000) self.assertEqual(a, c) - # Amerian Roulette + # American Roulette population = ['Red', 'Black', 'Green'] weights = [18, 18, 2] cum_weights = [18, 36, 38] diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py index 4444e94..5b53b82 100644 --- a/Lib/test/test_ssl.py +++ b/Lib/test/test_ssl.py @@ -4332,7 +4332,7 @@ class TestPostHandshakeAuth(unittest.TestCase): self.assertEqual(s.recv(1024), b'FALSE\n') s.write(b'PHA') self.assertEqual(s.recv(1024), b'OK\n') - # optional doens't fail when client does not have a cert + # optional doesn't fail when client does not have a cert s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'FALSE\n') diff --git a/Lib/test/test_tools/test_i18n.py b/Lib/test/test_tools/test_i18n.py index 8b2b90d..42e20f8 100644 --- a/Lib/test/test_tools/test_i18n.py +++ b/Lib/test/test_tools/test_i18n.py @@ -211,7 +211,7 @@ class Test_pygettext(unittest.TestCase): self.assertIn('doc3', msgids) def test_classdocstring_early_colon(self): - """ Test docstring extraction for a class with colons occuring within + """ Test docstring extraction for a class with colons occurring within the parentheses. """ msgids = self.extract_docstrings_from_str(dedent('''\ diff --git a/Lib/tokenize.py b/Lib/tokenize.py index cf1ecc9..0f9d5dd 100644 --- a/Lib/tokenize.py +++ b/Lib/tokenize.py @@ -82,7 +82,7 @@ Number = group(Imagnumber, Floatnumber, Intnumber) # Return the empty string, plus all of the valid string prefixes. def _all_string_prefixes(): # The valid string prefixes. Only contain the lower case versions, - # and don't contain any permuations (include 'fr', but not + # and don't contain any permutations (include 'fr', but not # 'rf'). The various permutations will be generated. _valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr'] # if we add binary f-strings, add: ['fb', 'fbr'] diff --git a/Lib/trace.py b/Lib/trace.py index fd40fba..63008a1 100755 --- a/Lib/trace.py +++ b/Lib/trace.py @@ -476,6 +476,7 @@ class Trace: if not self.donothing: sys.settrace(None) return result + runfunc.__text_signature__ = '($self, func, /, *args, **kw)' def file_module_function_of(self, frame): code = frame.f_code diff --git a/Lib/turtle.py b/Lib/turtle.py index 47a94f2..044d91c 100644 --- a/Lib/turtle.py +++ b/Lib/turtle.py @@ -1568,7 +1568,7 @@ class TNavigator(object): fullcircle - a number Set angle measurement units, i. e. set number - of 'degrees' for a full circle. Dafault value is + of 'degrees' for a full circle. Default value is 360 degrees. Example (for a Turtle instance named turtle): diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py index 8ff2546..8e01c3d 100644 --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -102,6 +102,7 @@ def addModuleCleanup(*args, **kwargs): args = tuple(args) _module_cleanups.append((function, args, kwargs)) +addModuleCleanup.__text_signature__ = '(function, /, *args, **kwargs)' def doModuleCleanups(): @@ -498,8 +499,8 @@ class TestCase(object): args = tuple(args) self._cleanups.append((function, args, kwargs)) + addCleanup.__text_signature__ = '($self, function, /, *args, **kwargs)' - @classmethod def addClassCleanup(*args, **kwargs): """Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).""" @@ -514,6 +515,8 @@ class TestCase(object): args = tuple(args) cls._class_cleanups.append((function, args, kwargs)) + addClassCleanup.__text_signature__ = '($cls, function, /, *args, **kwargs)' + addClassCleanup = classmethod(addClassCleanup) def setUp(self): "Hook method for setting up the test fixture before exercising it." diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index 351aba5..1e8057d 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -25,6 +25,7 @@ __all__ = ( __version__ = '1.0' +import io import inspect import pprint import sys @@ -2318,25 +2319,12 @@ MethodWrapperTypes = ( file_spec = None -def _iterate_read_data(read_data): - # Helper for mock_open: - # Retrieve lines from read_data via a generator so that separate calls to - # readline, read, and readlines are properly interleaved - sep = b'\n' if isinstance(read_data, bytes) else '\n' - data_as_list = [l + sep for l in read_data.split(sep)] - - if data_as_list[-1] == sep: - # If the last line ended in a newline, the list comprehension will have an - # extra entry that's just a newline. Remove this. - data_as_list = data_as_list[:-1] - else: - # If there wasn't an extra newline by itself, then the file being - # emulated doesn't have a newline to end the last line remove the - # newline that our naive format() added - data_as_list[-1] = data_as_list[-1][:-1] - for line in data_as_list: - yield line +def _to_stream(read_data): + if isinstance(read_data, bytes): + return io.BytesIO(read_data) + else: + return io.StringIO(read_data) def mock_open(mock=None, read_data=''): @@ -2351,20 +2339,23 @@ def mock_open(mock=None, read_data=''): `read_data` is a string for the `read`, `readline` and `readlines` of the file handle to return. This is an empty string by default. """ + _read_data = _to_stream(read_data) + _state = [_read_data, None] + def _readlines_side_effect(*args, **kwargs): if handle.readlines.return_value is not None: return handle.readlines.return_value - return list(_state[0]) + return _state[0].readlines(*args, **kwargs) def _read_side_effect(*args, **kwargs): if handle.read.return_value is not None: return handle.read.return_value - return type(read_data)().join(_state[0]) + return _state[0].read(*args, **kwargs) - def _readline_side_effect(): + def _readline_side_effect(*args, **kwargs): yield from _iter_side_effect() while True: - yield type(read_data)() + yield _state[0].readline(*args, **kwargs) def _iter_side_effect(): if handle.readline.return_value is not None: @@ -2384,8 +2375,6 @@ def mock_open(mock=None, read_data=''): handle = MagicMock(spec=file_spec) handle.__enter__.return_value = handle - _state = [_iterate_read_data(read_data), None] - handle.write.return_value = None handle.read.return_value = None handle.readline.return_value = None @@ -2398,7 +2387,7 @@ def mock_open(mock=None, read_data=''): handle.__iter__.side_effect = _iter_side_effect def reset_data(*args, **kwargs): - _state[0] = _iterate_read_data(read_data) + _state[0] = _to_stream(read_data) if handle.readline.side_effect == _state[1]: # Only reset the side effect if the user hasn't overridden it. _state[1] = _readline_side_effect() diff --git a/Lib/unittest/test/testmock/testwith.py b/Lib/unittest/test/testmock/testwith.py index 37100b8..5172c22 100644 --- a/Lib/unittest/test/testmock/testwith.py +++ b/Lib/unittest/test/testmock/testwith.py @@ -283,7 +283,12 @@ class TestMockOpen(unittest.TestCase): # for mocks returned by mock_open some_data = 'foo\nbar\nbaz' mock = mock_open(read_data=some_data) - self.assertEqual(mock().read(10), some_data) + self.assertEqual(mock().read(10), some_data[:10]) + self.assertEqual(mock().read(10), some_data[:10]) + + f = mock() + self.assertEqual(f.read(10), some_data[:10]) + self.assertEqual(f.read(10), some_data[10:]) def test_interleaved_reads(self): diff --git a/Lib/weakref.py b/Lib/weakref.py index 285c707..1eeb7b0 100644 --- a/Lib/weakref.py +++ b/Lib/weakref.py @@ -569,6 +569,7 @@ class finalize: info.index = next(self._index_iter) self._registry[self] = info finalize._dirty = True + __init__.__text_signature__ = '($self, obj, func, /, *args, **kwargs)' def __call__(self, _=None): """If alive then mark as dead and return func(*args, **kwargs); diff --git a/Lib/xmlrpc/client.py b/Lib/xmlrpc/client.py index a0e923a..b987574 100644 --- a/Lib/xmlrpc/client.py +++ b/Lib/xmlrpc/client.py @@ -186,8 +186,7 @@ INTERNAL_ERROR = -32603 class Error(Exception): """Base class for client errors.""" - def __str__(self): - return repr(self) + __str__ = object.__str__ ## # Indicates an HTTP-level protocol error. This is raised by the HTTP @@ -869,8 +868,6 @@ class MultiCall: def __repr__(self): return "<%s at %#x>" % (self.__class__.__name__, id(self)) - __str__ = __repr__ - def __getattr__(self, name): return _MultiCallMethod(self.__call_list, name) @@ -1468,8 +1465,6 @@ class ServerProxy: (self.__class__.__name__, self.__host, self.__handler) ) - __str__ = __repr__ - def __getattr__(self, name): # magic method dispatcher return _Method(self.__request, name) diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-04-10-18-12-11.bpo-36594.fbnJAc.rst b/Misc/NEWS.d/next/Core and Builtins/2019-04-10-18-12-11.bpo-36594.fbnJAc.rst new file mode 100644 index 0000000..7ca5dd9 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2019-04-10-18-12-11.bpo-36594.fbnJAc.rst @@ -0,0 +1,2 @@ +Fix incorrect use of ``%p`` in format strings. +Patch by Zackery Spytz. diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-05-04-16-15-33.bpo-36793.Izog4Z.rst b/Misc/NEWS.d/next/Core and Builtins/2019-05-04-16-15-33.bpo-36793.Izog4Z.rst new file mode 100644 index 0000000..6c79f97 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2019-05-04-16-15-33.bpo-36793.Izog4Z.rst @@ -0,0 +1,3 @@ +Removed ``__str__`` implementations from builtin types :class:`bool`, +:class:`int`, :class:`float`, :class:`complex` and few classes from the +standard library. They now inherit ``__str__()`` from :class:`object`. diff --git a/Misc/NEWS.d/next/Library/2019-01-11-17-09-15.bpo-31855.PlhfsX.rst b/Misc/NEWS.d/next/Library/2019-01-11-17-09-15.bpo-31855.PlhfsX.rst new file mode 100644 index 0000000..0da9c49 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-01-11-17-09-15.bpo-31855.PlhfsX.rst @@ -0,0 +1,2 @@ +:func:`unittest.mock.mock_open` results now respects the argument of read([size]). +Patch contributed by Rémi Lapeyre. diff --git a/Misc/NEWS.d/next/Library/2019-04-06-12-36-09.bpo-36542.Q0qyYV.rst b/Misc/NEWS.d/next/Library/2019-04-06-12-36-09.bpo-36542.Q0qyYV.rst new file mode 100644 index 0000000..8374776 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-04-06-12-36-09.bpo-36542.Q0qyYV.rst @@ -0,0 +1,2 @@ +The signature of Python functions can now be overridden by specifying the +``__text_signature__`` attribute. diff --git a/Misc/NEWS.d/next/Library/2019-05-05-16-14-38.bpo-36806.rAzF-x.rst b/Misc/NEWS.d/next/Library/2019-05-05-16-14-38.bpo-36806.rAzF-x.rst new file mode 100644 index 0000000..7e3ff6c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-05-05-16-14-38.bpo-36806.rAzF-x.rst @@ -0,0 +1,2 @@ +Forbid creation of asyncio stream objects like StreamReader, StreamWriter, +Process, and their protocols outside of asyncio package. diff --git a/Misc/NEWS.d/next/Tests/2019-05-06-18-29-54.bpo-35925.gwQPuC.rst b/Misc/NEWS.d/next/Tests/2019-05-06-18-29-54.bpo-35925.gwQPuC.rst new file mode 100644 index 0000000..ad8cc8f --- /dev/null +++ b/Misc/NEWS.d/next/Tests/2019-05-06-18-29-54.bpo-35925.gwQPuC.rst @@ -0,0 +1 @@ +Skip httplib and nntplib networking tests when they would otherwise fail due to a modern OS or distro with a default OpenSSL policy of rejecting connections to servers with weak certificates. diff --git a/Modules/_ctypes/_ctypes_test.c b/Modules/_ctypes/_ctypes_test.c index f842058..bae4976 100644 --- a/Modules/_ctypes/_ctypes_test.c +++ b/Modules/_ctypes/_ctypes_test.c @@ -87,7 +87,7 @@ EXPORT(void)testfunc_array(int values[4]) EXPORT(long double)testfunc_Ddd(double a, double b) { long double result = (long double)(a * b); - printf("testfunc_Ddd(%p, %p)\n", &a, &b); + printf("testfunc_Ddd(%p, %p)\n", (void *)&a, (void *)&b); printf("testfunc_Ddd(%g, %g)\n", a, b); return result; } @@ -95,7 +95,7 @@ EXPORT(long double)testfunc_Ddd(double a, double b) EXPORT(long double)testfunc_DDD(long double a, long double b) { long double result = a * b; - printf("testfunc_DDD(%p, %p)\n", &a, &b); + printf("testfunc_DDD(%p, %p)\n", (void *)&a, (void *)&b); printf("testfunc_DDD(%Lg, %Lg)\n", a, b); return result; } @@ -103,7 +103,7 @@ EXPORT(long double)testfunc_DDD(long double a, long double b) EXPORT(int)testfunc_iii(int a, int b) { int result = a * b; - printf("testfunc_iii(%p, %p)\n", &a, &b); + printf("testfunc_iii(%p, %p)\n", (void *)&a, (void *)&b); return result; } @@ -361,7 +361,7 @@ static void _xxx_init(void *(*Xalloc)(int), void (*Xfree)(void *)) { void *ptr; - printf("_xxx_init got %p %p\n", Xalloc, Xfree); + printf("_xxx_init got %p %p\n", (void *)Xalloc, (void *)Xfree); printf("calling\n"); ptr = Xalloc(32); Xfree(ptr); diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c index 1ad842e..a8ba84b 100644 --- a/Modules/_ctypes/callproc.c +++ b/Modules/_ctypes/callproc.c @@ -531,11 +531,11 @@ PyCArg_repr(PyCArgObject *self) default: if (is_literal_char((unsigned char)self->tag)) { sprintf(buffer, "<cparam '%c' at %p>", - (unsigned char)self->tag, self); + (unsigned char)self->tag, (void *)self); } else { sprintf(buffer, "<cparam 0x%02x at %p>", - (unsigned char)self->tag, self); + (unsigned char)self->tag, (void *)self); } break; } diff --git a/Modules/_decimal/_decimal.c b/Modules/_decimal/_decimal.c index 51aed2c..d977b14 100644 --- a/Modules/_decimal/_decimal.c +++ b/Modules/_decimal/_decimal.c @@ -5390,7 +5390,7 @@ static PyTypeObject PyDecContext_Type = 0, /* tp_as_mapping */ (hashfunc) 0, /* tp_hash */ 0, /* tp_call */ - (reprfunc) context_repr, /* tp_str */ + 0, /* tp_str */ (getattrofunc) context_getattr, /* tp_getattro */ (setattrofunc) context_setattr, /* tp_setattro */ (PyBufferProcs *) 0, /* tp_as_buffer */ diff --git a/Modules/_json.c b/Modules/_json.c index 2d7c1bf..4faa9cc 100644 --- a/Modules/_json.c +++ b/Modules/_json.c @@ -1482,7 +1482,7 @@ encoder_listencode_obj(PyEncoderObject *s, _PyAccu *acc, return _steal_accumulate(acc, encoded); } else if (PyLong_Check(obj)) { - PyObject *encoded = PyLong_Type.tp_str(obj); + PyObject *encoded = PyLong_Type.tp_repr(obj); if (encoded == NULL) return -1; return _steal_accumulate(acc, encoded); @@ -1646,7 +1646,7 @@ encoder_listencode_dict(PyEncoderObject *s, _PyAccu *acc, goto bail; } else if (PyLong_Check(key)) { - kstr = PyLong_Type.tp_str(key); + kstr = PyLong_Type.tp_repr(key); if (kstr == NULL) { goto bail; } diff --git a/Modules/_xxsubinterpretersmodule.c b/Modules/_xxsubinterpretersmodule.c index 1cf43b7..0d8e5f3 100644 --- a/Modules/_xxsubinterpretersmodule.c +++ b/Modules/_xxsubinterpretersmodule.c @@ -1250,7 +1250,7 @@ _channel_finish_closing(struct _channel *chan) { // Do the things that would have been done in _channels_close(). ref->chan = NULL; _channel_free(chan); -}; +} /* "high"-level channel-related functions */ diff --git a/Modules/hashtable.c b/Modules/hashtable.c index e6f8daf..4a36a1e 100644 --- a/Modules/hashtable.c +++ b/Modules/hashtable.c @@ -240,7 +240,7 @@ _Py_hashtable_print_stats(_Py_hashtable_t *ht) } printf("hash table %p: entries=%" PY_FORMAT_SIZE_T "u/%" PY_FORMAT_SIZE_T "u (%.0f%%), ", - ht, ht->entries, ht->num_buckets, load * 100.0); + (void *)ht, ht->entries, ht->num_buckets, load * 100.0); if (nchains) printf("avg_chain_len=%.1f, ", (double)total_chain_len / nchains); printf("max_chain_len=%" PY_FORMAT_SIZE_T "u, %" PY_FORMAT_SIZE_T "u KiB\n", diff --git a/Objects/boolobject.c b/Objects/boolobject.c index b92fafe..508ea61 100644 --- a/Objects/boolobject.c +++ b/Objects/boolobject.c @@ -147,7 +147,7 @@ PyTypeObject PyBool_Type = { 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ - bool_repr, /* tp_str */ + 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ diff --git a/Objects/complexobject.c b/Objects/complexobject.c index 6e3d47b..cae2bf1 100644 --- a/Objects/complexobject.c +++ b/Objects/complexobject.c @@ -1129,7 +1129,7 @@ PyTypeObject PyComplex_Type = { 0, /* tp_as_mapping */ (hashfunc)complex_hash, /* tp_hash */ 0, /* tp_call */ - (reprfunc)complex_repr, /* tp_str */ + 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ diff --git a/Objects/floatobject.c b/Objects/floatobject.c index b952df8..adb9b80 100644 --- a/Objects/floatobject.c +++ b/Objects/floatobject.c @@ -1923,7 +1923,7 @@ PyTypeObject PyFloat_Type = { 0, /* tp_as_mapping */ (hashfunc)float_hash, /* tp_hash */ 0, /* tp_call */ - (reprfunc)float_repr, /* tp_str */ + 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ diff --git a/Objects/longobject.c b/Objects/longobject.c index da697a7..9fb1fb0 100644 --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -5592,7 +5592,7 @@ PyTypeObject PyLong_Type = { 0, /* tp_as_mapping */ (hashfunc)long_hash, /* tp_hash */ 0, /* tp_call */ - long_to_decimal_string, /* tp_str */ + 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ diff --git a/Objects/object.c b/Objects/object.c index 589bf36..cb72794 100644 --- a/Objects/object.c +++ b/Objects/object.c @@ -385,7 +385,7 @@ PyObject_Print(PyObject *op, FILE *fp, int flags) universally available */ Py_BEGIN_ALLOW_THREADS fprintf(fp, "<refcnt %ld at %p>", - (long)op->ob_refcnt, op); + (long)op->ob_refcnt, (void *)op); Py_END_ALLOW_THREADS } else { @@ -499,7 +499,7 @@ _PyObject_Dump(PyObject* op) "address : %p\n", Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, (long)op->ob_refcnt, - op); + (void *)op); fflush(stderr); } @@ -1894,7 +1894,7 @@ _Py_PrintReferences(FILE *fp) PyObject *op; fprintf(fp, "Remaining objects:\n"); for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { - fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); + fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", (void *)op, op->ob_refcnt); if (PyObject_Print(op, fp, 0) != 0) PyErr_Clear(); putc('\n', fp); @@ -1910,7 +1910,7 @@ _Py_PrintReferenceAddresses(FILE *fp) PyObject *op; fprintf(fp, "Remaining object addresses:\n"); for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) - fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, + fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", (void *)op, op->ob_refcnt, Py_TYPE(op)->tp_name); } @@ -2167,10 +2167,10 @@ _PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg, fprintf(stderr, "<object: ob_type=NULL>\n"); } else if (_PyObject_IsFreed((PyObject *)Py_TYPE(obj))) { - fprintf(stderr, "<object: freed type %p>\n", Py_TYPE(obj)); + fprintf(stderr, "<object: freed type %p>\n", (void *)Py_TYPE(obj)); } else { - /* Diplay the traceback where the object has been allocated. + /* Display the traceback where the object has been allocated. Do it before dumping repr(obj), since repr() is more likely to crash than dumping the traceback. */ void *ptr; diff --git a/Objects/obmalloc.c b/Objects/obmalloc.c index 3ee1435..7cfd289 100644 --- a/Objects/obmalloc.c +++ b/Objects/obmalloc.c @@ -2354,7 +2354,7 @@ _PyObject_DebugDumpAddress(const void *p) } tail = q + nbytes; - fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); + fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, (void *)tail); ok = 1; for (i = 0; i < SST; ++i) { if (tail[i] != FORBIDDENBYTE) { diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index 4d86519e8..eaba583 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -1251,7 +1251,7 @@ void *_PyUnicode_compact_data(void *unicode_raw) { } void *_PyUnicode_data(void *unicode_raw) { PyObject *unicode = _PyObject_CAST(unicode_raw); - printf("obj %p\n", unicode); + printf("obj %p\n", (void*)unicode); printf("compact %d\n", PyUnicode_IS_COMPACT(unicode)); printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode)); printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1))); @@ -1282,14 +1282,14 @@ _PyUnicode_Dump(PyObject *op) if (ascii->wstr == data) printf("shared "); - printf("wstr=%p", ascii->wstr); + printf("wstr=%p", (void *)ascii->wstr); if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) { printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length); if (!ascii->state.compact && compact->utf8 == unicode->data.any) printf("shared "); printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)", - compact->utf8, compact->utf8_length); + (void *)compact->utf8, compact->utf8_length); } printf(", data=%p\n", data); } diff --git a/Programs/_freeze_importlib.c b/Programs/_freeze_importlib.c index 0818012..4b2ed70 100644 --- a/Programs/_freeze_importlib.c +++ b/Programs/_freeze_importlib.c @@ -127,7 +127,7 @@ main(int argc, char *argv[]) size_t i, end = Py_MIN(n + 16, data_size); fprintf(outfile, " "); for (i = n; i < end; i++) { - fprintf(outfile, "%d,", (unsigned int) data[i]); + fprintf(outfile, "%u,", (unsigned int) data[i]); } fprintf(outfile, "\n"); } diff --git a/Python/sysmodule.c b/Python/sysmodule.c index fbdeb9b..1290164 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -1750,7 +1750,7 @@ _alloc_preinit_entry(const wchar_t *value) PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc); return node; -}; +} static int _append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value) @@ -1772,7 +1772,7 @@ _append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value) last_entry->next = new_entry; } return 0; -}; +} static void _clear_preinit_entries(_Py_PreInitEntry *optionlist) @@ -1789,7 +1789,7 @@ _clear_preinit_entries(_Py_PreInitEntry *optionlist) current = next; } PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc); -}; +} static void _clear_all_preinit_options(void) @@ -1820,7 +1820,7 @@ _PySys_ReadPreInitOptions(void) _clear_all_preinit_options(); return 0; -}; +} static PyObject * get_warnoptions(void) diff --git a/Python/thread_pthread.h b/Python/thread_pthread.h index 1f4f36d..4c106d9 100644 --- a/Python/thread_pthread.h +++ b/Python/thread_pthread.h @@ -339,7 +339,7 @@ PyThread_allocate_lock(void) } } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + dprintf(("PyThread_allocate_lock() -> %p\n", (void *)lock)); return (PyThread_type_lock)lock; } @@ -521,7 +521,7 @@ PyThread_allocate_lock(void) } } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + dprintf(("PyThread_allocate_lock() -> %p\n", (void *)lock)); return (PyThread_type_lock) lock; } |
