8000 Merge branch 'main' into fix-exeptions-append-after-cancel-async-stagger · python/cpython@dd55eae · GitHub
[go: up one dir, main page]

Skip to content

Commit dd55eae

Browse files
authored
Merge branch 'main' into fix-exeptions-append-after-cancel-async-stagger
2 parents 4a4c027 + fd94c6a commit dd55eae

File tree

5 files changed

+276
-240
lines changed
Original file line numberDiff line numberDiff line change
@@ -151,69 +151,91 @@ Basic Usage
151151
sort_keys=False, **kw)
152152
153153
Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
154-
:term:`file-like object`) using this :ref:`conversion table
154+
:term:`file-like object`) using this :ref:`Python-to-JSON conversion table
155155
<py-to-json-table>`.
156156

157-
If *skipkeys* is true (default: ``False``), then dict keys that are not
158-
of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`,
159-
``None``) will be skipped instead of raising a :exc:`TypeError`.
160-
161-
The :mod:`json` module always produces :class:`str` objects, not
162-
:class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str`
163-
input.
164-
165-
If *ensure_ascii* is true (the default), the output is guaranteed to
166-
have all incoming non-ASCII characters escaped. If *ensure_ascii* is
167-
false, these characters will be output as-is.
157+
To use a custom :class:`JSONEncoder` subclass (for example, one that overrides the
158+
:meth:`~JSONEncoder.default` method to serialize additional types), specify it with the
159+
*cls* keyword argument; otherwise :class:`JSONEncoder` is used.
168160

169-
If *check_circular* is false (default: ``True``), then the circular
170-
reference check for container types will be skipped and a circular reference
171-
will result in a :exc:`RecursionError` (or worse).
161+
.. note::
172162

173-
If *allow_nan* is false (default: ``True``), then it will be a
174-
:exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
175-
``inf``, ``-inf``) in strict compliance of the JSON specification.
176-
If *allow_nan* is true, their JavaScript equivalents (``NaN``,
177-
``Infinity``, ``-Infinity``) will be used.
163+
Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol,
164+
so trying to serialize multiple objects with repeated calls to
165+
:func:`dump` using the same *fp* will result in an invalid JSON file.
178166

179-
If *indent* is a non-negative integer or string, then JSON array elements and
180-
object members will be pretty-printed with that indent level. An indent level
181-
of 0, negative, or ``""`` will only insert newlines. ``None`` (the default)
182-
selects the most compact representation. Using a positive integer indent
183-
indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
184-
that string is used to indent each level.
167+
:param object obj:
168+
The Python object to be serialized.
169+
170+
:param fp:
171+
The file-like object *obj* will be serialized to.
172+
The :mod:`!json` module always produces :class:`str` objects,
173+
not :class:`bytes` objects,
174+
therefore ``fp.write()`` must support :class:`str` input.
175+
:type fp: :term:`file-like object`
176+
177+
:param bool skipkeys:
178+
If ``True``, keys that are not of a basic type
179+
(:class:`str`, :class:`int`, :class:`float`, :class:`bool`, ``None``)
180+
will be skipped instead of raising a :exc:`TypeError`.
181+
Default ``False``.
182+
183+
:param bool ensure_ascii:
184+
If ``True`` (the default), the output is guaranteed to
185+
have all incoming non-ASCII characters escaped.
186+
If ``False``, these characters will be outputted as-is.
187+
188+
:param bool check_circular:
189+
If ``False``, the circular reference check for container types is skipped
190+
and a circular reference will result in a :exc:`RecursionError` (or worse).
191+
Default ``True``.
192+
193+
:param bool allow_nan:
194+
If ``False``, serialization of out-of-range :class:`float` values
195+
(``nan``, ``inf``, ``-inf``) will result in a :exc:`ValueError`,
196+
in strict compliance with the JSON specification.
197+
If ``True`` (the default), their JavaScript equivalents
198+
(``NaN``, ``Infinity``, ``-Infinity``) are used.
199+
200+
:param indent:
201+
If a positive integer or string, JSON array elements and
202+
object members will be pretty-printed with that indent level.
203+
A positive integer indents that many spaces per level;
204+
a string (such as ``"\t"``) is used to indent each level.
205+
If zero, negative, or ``""`` (the empty string),
206+
only newlines are inserted.
207+
If ``None`` (the default), the most compact representation is used.
208+
:type indent: int | str | None
209+
210+
:param separators:
211+
A two-tuple: ``(item_separator, key_separator)``.
212+
If ``None`` (the default), *separators* defaults to
213+
``(', ', ': ')`` if *indent* is ``None``,
214+
and ``(',', ': ')`` otherwise.
215+
For the most compact JSON,
216+
specify ``(',', ':')`` to eliminate whitespace.
217+
:type separators: tuple | None
218+
219+
:param default:
220+
A function that is called for objects that can't otherwise be serialized.
221+
It should return a JSON encodable version of the object
222+
or raise a :exc:`TypeError`.
223+
If ``None`` (the default), :exc:`!TypeError` is raised.
224+
:type default: :term:`callable` | None
225+
226+
:param sort_keys:
227+
If ``True``, dictionaries will be outputted sorted by key.
228+
Default ``False``.
185229

186230
.. versionchanged:: 3.2
187231
Allow strings for *indent* in addition to integers.
188232

189-
If specified, *separators* should be an ``(item_separator, key_separator)``
190-
tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
191-
``(',', ': ')`` otherwise. To get the most compact JSON representation,
192-
you should specify ``(',', ':')`` to eliminate whitespace.
193-
194233
.. versionchanged:: 3.4
195234
Use ``(',', ': ')`` as default if *indent* is not ``None``.
196235

197-
If specified, *default* should be a function that gets called for objects that
198-
can't otherwise be serialized. It should return a JSON encodable version of
199-
the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError`
200-
is raised.
201-
202-
If *sort_keys* is true (default: ``False``), then the output of
203-
dictionaries will be sorted by key.
204-
205-
To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
206-
:meth:`~JSONEncoder.default` method to serialize additional types), specify it with the
207-
*cls* kwarg; otherwise :class:`JSONEncoder` is used.
208-
209236
.. versionchanged:: 3.6
210237
All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`.
211238

212-
.. note::
213-
214-
Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol,
215-
so trying to serialize multiple objects with repeated calls to
216-
:func:`dump` using the same *fp* will result in an invalid JSON file.
217239

218240
.. function:: dumps(obj, *, skipkeys=False, ensure_ascii=True, \
219241
check_circular=True, allow_nan=True, cls=None, \
Original file line numberDiff line numberDiff line change
@@ -573,30 +573,3 @@ def copy_into(self, target_dir, *, follow_symlinks=True,
573573
return self.copy(target, follow_symlinks=follow_symlinks,
574574
dirs_exist_ok=dirs_exist_ok,
575575
preserve_metadata=preserve_metadata)
576-
577-
def _delete(self):
578-
"""
579-
Delete this file or directory (including all sub-directories).
580-
"""
581-
raise NotImplementedError
582-
583-
def move(self, target):
584-
"""
585-
Recursively move this file or directory tree to the given destination.
586-
"""
587-
target = self.copy(target, follow_symlinks=False, preserve_metadata=True)
588-
self._delete()
589-
return target
590-
591-
def move_into(self, target_dir):
592-
"""
593-
Move this file or directory tree into the given existing directory.
594-
"""
595-
name = self.name
596-
if not name:
597-
raise ValueError(f"{self!r} has an empty name")
598-
elif isinstance(target_dir, PathBase):
599-
target = target_dir / name
600-
else:
601-
target = self.with_segments(target_dir, name)
602-
return self.move(target)
Original file line numberDiff line numberDiff line change
@@ -1128,16 +1128,38 @@ def move(self, target):
11281128
"""
11291129
Recursively move this file or directory tree to the given destination.
11301130
"""
1131-
if not isinstance(target, PathBase):
1132-
target = self.with_segments(target)
1133-
target.copy._ensure_different_file(self)
1131+
# Use os.replace() if the target is os.PathLike and on the same FS.
11341132
try:
1135-
return self.replace(target)
1136-
except OSError as err:
1137-
if err.errno != EXDEV:
1138-
raise
1133+
target_str = os.fspath(target)
1134+
except TypeError:
1135+
pass
1136+
else:
1137+
if not isinstance(target, PathBase):
1138+
target = self.with_segments(target_str)
1139+
target.copy._ensure_different_file(self)
1140+
try:
1141+
os.replace(self, target_str)
1142+
return target
1143+
except OSError as err:
1144+
if err.errno != EXDEV:
1145+
raise
11391146
# Fall back to copy+delete.
1140-
return PathBase.move(self, target)
1147+
target = self.copy(target, follow_symlinks=False, preserve_metadata=True)
1148+
self._delete()
1149+
return target
1150+
1151+
def move_into(self, target_dir):
1152+
"""
1153+
Move this file or directory tree into the given existing directory.
1154+
"""
1155+
name = self.name
1156+
if not name:
1157+
raise ValueError(f"{self!r} has an empty name")
1158+
elif isinstance(target_dir, PathBase):
1159+
target = target_dir / name
1160+
else:
1161+
target = self.with_segments(target_dir, name)
1162+
return self.move(target)
11411163

11421164
if hasattr(os, "symlink"):
11431165
def symlink_to(self, target, target_is_directory=False):