Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Doc/c-api/module.rst
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,15 @@ Feature slots
If ``Py_mod_multiple_interpreters`` is not specified, the import
machinery defaults to ``Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED``.

For historical reasons, the values are declared as pointers (``void *``).
When using :c:type:`PySlot` arrays, use :c:macro:`PySlot_DATA` for
:c:macro:`!Py_mod_multiple_interpreters`:

.. code-block:: c

PySlot_DATA(Py_mod_multiple_interpreters,
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED)

.. versionadded:: 3.12

.. c:macro:: Py_mod_gil
Expand All @@ -272,6 +281,14 @@ Feature slots
If ``Py_mod_gil`` is not specified, the import machinery defaults to
``Py_MOD_GIL_USED``.

For historical reasons, the values are declared as pointers (``void *``).
When using :c:type:`PySlot` arrays, use :c:macro:`PySlot_DATA` for
:c:macro:`!Py_mod_gil`:

.. code-block:: c

PySlot_DATA(Py_mod_gil, Py_MOD_GIL_NOT_USED)

.. versionadded:: 3.13


Expand Down
12 changes: 10 additions & 2 deletions Doc/c-api/weakref.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ as much as it can.
should accept a single parameter, which will be the weak reference object
itself. *callback* may also be ``None`` or ``NULL``. If *ob* is not a
weakly referenceable object, or if *callback* is not callable, ``None``, or
``NULL``, this will return ``NULL`` and raise :exc:`TypeError`.
``NULL``, this will raise :exc:`TypeError` and return ``NULL``.

.. versionchanged:: next
Raise :exc:`!TypeError` if *callback* is not callable, ``None``, or
``NULL``.

.. seealso::
:c:func:`PyType_SUPPORTS_WEAKREFS` for checking if *ob* is weakly
Expand All @@ -59,7 +63,11 @@ as much as it can.
collected; it should accept a single parameter, which will be the weak
reference object itself. *callback* may also be ``None`` or ``NULL``. If *ob*
is not a weakly referenceable object, or if *callback* is not callable,
``None``, or ``NULL``, this will return ``NULL`` and raise :exc:`TypeError`.
``NULL``, this will raise :exc:`TypeError` and return ``NULL``.

.. versionchanged:: next
Raise :exc:`!TypeError` if *callback* is not callable, ``None``, or
``NULL``.

.. seealso::
:c:func:`PyType_SUPPORTS_WEAKREFS` for checking if *ob* is weakly
Expand Down
6 changes: 6 additions & 0 deletions Doc/library/weakref.rst
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ See :ref:`__slots__ documentation <slots>` for details.
.. versionchanged:: 3.4
Added the :attr:`__callback__` attribute.

.. versionchanged:: next
Raise :exc:`!TypeError` if *callback* is not callable or ``None``.


.. function:: proxy(object[, callback])

Expand All @@ -151,6 +154,9 @@ See :ref:`__slots__ documentation <slots>` for details.
Extended the operator support on proxy objects to include the matrix
multiplication operators ``@`` and ``@=``.

.. versionchanged:: next
Raise :exc:`!TypeError` if *callback* is not callable or ``None``.


.. function:: getweakrefcount(object)

Expand Down
2 changes: 1 addition & 1 deletion Lib/_pyrepl/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ def is_soft_keyword_used(*tokens: TI | None) -> bool:
None | TI(T.NEWLINE) | TI(T.INDENT) | TI(T.DEDENT) | TI(string=":"),
TI(string="case"),
TI(T.NUMBER | T.STRING | T.FSTRING_START | T.TSTRING_START)
| TI(T.OP, string="(" | "*" | "-" | "[" | "{")
| TI(T.OP, string="(" | "*" | "-" | "+" | "[" | "{")
):
return True
case (
Expand Down
17 changes: 16 additions & 1 deletion Lib/pydoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1240,6 +1240,17 @@ def indent(self, text, prefix=' '):
lines = [(prefix + line).rstrip() for line in text.split('\n')]
return '\n'.join(lines)

def _format_doc(self, text, width=68):
"""Wraps the single-line summary if it is too long."""
if not text: return ''
lines = text.split('\n', 2)
if len(lines) > 1 and lines[1]:
return text
lines[:1] = textwrap.wrap(lines[0], width,
break_long_words=False,
break_on_hyphens=False)
return '\n'.join(lines)

def section(self, title, contents):
"""Format a section with a given heading."""
clean_contents = self.indent(contents).rstrip()
Expand Down Expand Up @@ -1390,6 +1401,7 @@ def makename(c, m=object.__module__):

doc = getdoc(object)
if doc:
doc = self._format_doc(doc)
push(doc + '\n')

# List the mro, if non-trivial.
Expand Down Expand Up @@ -1590,6 +1602,7 @@ def docroutine(self, object, name=None, mod=None, cl=None, homecls=None):
return decl + '\n'
else:
doc = getdoc(object) or ''
doc = self._format_doc(doc)
return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')

def docdata(self, object, name=None, mod=None, cl=None, *ignored):
Expand All @@ -1602,6 +1615,7 @@ def docdata(self, object, name=None, mod=None, cl=None, *ignored):
push('\n')
doc = getdoc(object) or ''
if doc:
doc = self._format_doc(doc)
push(self.indent(doc))
push('\n')
return ''.join(results)
Expand All @@ -1620,7 +1634,8 @@ def docother(self, object, name=None, mod=None, parent=None, *ignored,
if not doc:
doc = getdoc(object)
if doc:
line += '\n' + self.indent(str(doc)) + '\n'
doc = self._format_doc(str(doc))
line += '\n' + self.indent(doc) + '\n'
return line

class _PlainTextDoc(TextDoc):
Expand Down
2 changes: 2 additions & 0 deletions Lib/test/test_capi/test_weakref.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def test_pyweakref_newref(self):
# PyWeakref_NewRef() handles None callback as NULL callback
wr = newref(obj, None)
self.assertIs(type(wr), weakref.ReferenceType)
self.assertRaises(TypeError, newref, obj, 42)
log = []
wr = newref(obj, log.append)
self.assertIs(type(wr), weakref.ReferenceType)
Expand All @@ -116,6 +117,7 @@ def test_pyweakref_newproxy(self):
# PyWeakref_NewProxy() handles None callback as NULL callback
wp = newproxy(obj, None)
self.assertIs(type(wp), weakref.ProxyType)
self.assertRaises(TypeError, newproxy, obj, 42)
log = []
wp = newproxy(obj, log.append)
self.assertIs(type(wp), weakref.ProxyType)
Expand Down
29 changes: 28 additions & 1 deletion Lib/test/test_dtrace.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,11 +378,14 @@ def setUpClass(cls):
def get_readelf_version():
try:
cmd = ["readelf", "--version"]
# Force the C locale to disable localization.
env = dict(os.environ, LC_ALL="C")
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
env=env,
)
with proc:
version, stderr = proc.communicate()
Expand All @@ -405,12 +408,36 @@ def get_readelf_version():
return int(match.group(1)), int(match.group(2))

def get_readelf_output(self):
command = ["readelf", "-n", sys.executable]
binary = sys.executable
if sysconfig.get_config_var("Py_ENABLE_SHARED"):
lib_dir = sysconfig.get_config_var("LIBDIR")
if not lib_dir or sysconfig.is_python_build():
lib_dir = os.path.abspath(os.path.dirname(sys.executable))

lib_names = []
for name in (
sysconfig.get_config_var("INSTSONAME"),
sysconfig.get_config_var("LDLIBRARY"),
):
if name and name not in lib_names:
lib_names.append(name)

if lib_dir:
for name in lib_names:
libpython_path = os.path.join(lib_dir, name)
if os.path.exists(libpython_path):
binary = libpython_path
break

command = ["readelf", "-n", binary]
# Force the C locale to disable localization.
env = dict(os.environ, LC_ALL="C")
stdout, _ = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
env=env,
).communicate()
return stdout

Expand Down
29 changes: 29 additions & 0 deletions Lib/test/test_pydoc/longsummary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class C:
"""This is a class summary that consists of a very long single line, exceeding the recommended PEP 8 limit.

The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.
"""
def meth(self):
"""This is a method summary that consists of a very long single line, exceeding the recommended PEP 8 limit.

The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.
"""

@property
def prop(self):
"""This is a property summary that consists of a very long single line, exceeding the recommended PEP 8 limit.

The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.
"""

def func(self):
"""This is a function summary that consists of a very long single line, exceeding the recommended PEP 8 limit.

The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.
"""

data = C()
data.__doc__ = """This is a data summary that consists of a very long single line, exceeding the recommended PEP 8 limit.

The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.
"""
65 changes: 65 additions & 0 deletions Lib/test/test_pydoc/test_pydoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1245,6 +1245,71 @@ def function_with_really_long_name_so_annotations_can_be_rather_small(
<lambda> lambda very_long_parameter_name_that_should_not_fit_into_a_single_line, second_very_long_parameter_name
''' % __name__)

@requires_docstrings
def test_long_summaries(self):
from . import longsummary
doc = pydoc.render_doc(longsummary)
doc = clean_text(doc)
self.assertEqual(doc, '''Python Library Documentation: module test.test_pydoc.longsummary in test.test_pydoc

NAME
test.test_pydoc.longsummary

CLASSES
builtins.object
C

class C(builtins.object)
| This is a class summary that consists of a very long single line,
| exceeding the recommended PEP 8 limit.
|
| The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.
|
| Methods defined here:
|
| meth(self)
| This is a method summary that consists of a very long single line,
| exceeding the recommended PEP 8 limit.
|
| The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| prop
| This is a property summary that consists of a very long single line,
| exceeding the recommended PEP 8 limit.
|
| The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object

FUNCTIONS
func(self)
This is a function summary that consists of a very long single line,
exceeding the recommended PEP 8 limit.

The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.

DATA
data = <test.test_pydoc.longsummary.C object>
This is a data summary that consists of a very long single line,
exceeding the recommended PEP 8 limit.

The rest of the docstring body, separated from the summary by a blank line, can also contain very long lines.

FILE
%s

''' % inspect.getabsfile(longsummary))

def test__future__imports(self):
# __future__ features are excluded from module help,
# except when it's the __future__ module itself
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_pyrepl/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,14 @@ def test_gen_colors_keyword_highlighting(self):
("import", "keyword"),
],
),
(
"case +1",
[
("case", "soft_keyword"),
("+", "op"),
("1", "number"),
],
),
]
for code, expected_highlights in cases:
with self.subTest(code=code):
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def test_recursion_error_during_traceback(self):
sys.setrecursionlimit(15)
def f():
ref(lambda: 0, [])
ref(lambda: 0, ord)
f()
try:
Expand Down
45 changes: 45 additions & 0 deletions Lib/test/test_venv.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,51 @@ def test_unicode_in_batch_file(self):
)
self.assertEqual(out.strip(), '0')

@unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
def test_activate_bat_respects_disable_prompt(self):
rmtree(self.env_dir)
env_dir = os.path.join(os.path.realpath(self.env_dir), 'venv')
builder = venv.EnvBuilder(clear=True)
builder.create(env_dir)
activate = os.path.join(env_dir, self.bindir, 'activate.bat')
test_batch = os.path.join(self.env_dir, 'test_disable_prompt.bat')
with open(test_batch, "w") as f:
f.write('@echo off\n'
'set "PROMPT=base$G"\n'
'set "VIRTUAL_ENV_DISABLE_PROMPT=1"\n'
f'call "{activate}"\n'
'echo ACTIVE_PROMPT:%PROMPT%\n'
'echo VIRTUAL_ENV:%VIRTUAL_ENV%\n'
'set "PROMPT=changed$G"\n'
'call deactivate\n'
'echo FINAL_PROMPT:%PROMPT%\n')
out, err = check_output([test_batch])
lines = out.splitlines()
self.assertEqual(lines[0], b'ACTIVE_PROMPT:base$G')
self.assertEndsWith(lines[1], os.fsencode(env_dir))
self.assertEqual(lines[2], b'FINAL_PROMPT:changed$G')

@unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
def test_activate_bat_prefixes_prompt_by_default(self):
rmtree(self.env_dir)
env_dir = os.path.join(os.path.realpath(self.env_dir), 'venv')
builder = venv.EnvBuilder(clear=True)
builder.create(env_dir)
activate = os.path.join(env_dir, self.bindir, 'activate.bat')
test_batch = os.path.join(self.env_dir, 'test_enable_prompt.bat')
with open(test_batch, "w") as f:
f.write('@echo off\n'
'set "PROMPT=base) $G"\n'
'set "VIRTUAL_ENV_DISABLE_PROMPT="\n'
f'call "{activate}"\n'
'echo ACTIVE_PROMPT:%PROMPT%\n'
'call deactivate\n'
'echo FINAL_PROMPT:%PROMPT%\n')
out, err = check_output([test_batch])
lines = out.splitlines()
self.assertEqual(lines[0], b'ACTIVE_PROMPT:(venv) base) $G')
self.assertEqual(lines[1], b'FINAL_PROMPT:base) $G')

@unittest.skipUnless(os.name == 'nt' and can_symlink(),
'symlinks on Windows')
def test_failed_symlink(self):
Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_weakref.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ def test_basic_callback(self):
self.check_basic_callback(create_function)
self.check_basic_callback(create_bound_method)

def test_non_callable_callback(self):
c = C()
self.assertRaises(TypeError, weakref.ref, c, 42)
self.assertRaises(TypeError, weakref.proxy, c, 42)

@support.cpython_only
def test_cfunction(self):
_testcapi = import_helper.import_module("_testcapi")
Expand Down
Loading
Loading