Skip to content

Commit 2726e68

Browse files
committed
GH-65961: Stop setting __package__ on modules
1 parent fa9519f commit 2726e68

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+97
-274
lines changed

Doc/c-api/extension-modules.rst

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,8 @@ The process of creating an extension module follows several phases:
134134
- By default, Python itself then creates the module object -- that is, it does
135135
the equivalent of calling :py:meth:`~object.__new__` when creating an object.
136136
This step can be overridden using the :c:data:`Py_mod_create` slot.
137-
- Python sets initial module attributes like :attr:`~module.__package__` and
138-
:attr:`~module.__loader__`, and inserts the module object into
139-
:py:attr:`sys.modules`.
137+
- Python sets initial module attributes like :attr:`~module.__spec__`, and
138+
inserts the module object into :py:attr:`sys.modules`.
140139
- Afterwards, the module object is initialized in an extension-specific way
141140
-- the equivalent of :py:meth:`~object.__init__` when creating an object,
142141
or of executing top-level code in a Python-language module.

Doc/c-api/module.rst

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,13 @@ Module Objects
3333
single: __name__ (module attribute)
3434
single: __doc__ (module attribute)
3535
single: __file__ (module attribute)
36-
single: __package__ (module attribute)
3736
single: __loader__ (module attribute)
3837
3938
Return a new module object with :attr:`module.__name__` set to *name*.
40-
The module's :attr:`!__name__`, :attr:`~module.__doc__`,
41-
:attr:`~module.__package__` and :attr:`~module.__loader__` attributes are
42-
filled in (all but :attr:`!__name__` are set to ``None``). The caller is
43-
responsible for setting a :attr:`~module.__file__` attribute.
39+
The module's :attr:`!__name__`, :attr:`~module.__doc__`, and
40+
:attr:`~module.__loader__` attributes are filled in (all but
41+
:attr:`!__name__` are set to ``None``). The caller is responsible for
42+
setting a :attr:`~module.__file__` attribute.
4443
4544
Return ``NULL`` with an exception set on error.
4645
@@ -50,6 +49,9 @@ Module Objects
5049
:attr:`~module.__package__` and :attr:`~module.__loader__` are now set to
5150
``None``.
5251
52+
.. versionchanged:: 3.15
53+
:attr:`~module.__package__` is no longer set.
54+
5355
5456
.. c:function:: PyObject* PyModule_New(const char *name)
5557

Doc/deprecations/pending-removal-in-3.15.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ Pending removal in Python 3.15
1010

1111
* Setting :attr:`~module.__package__` on a module while
1212
failing to set :attr:`__spec__.parent <importlib.machinery.ModuleSpec.parent>`
13-
is deprecated. In Python 3.15, :attr:`!__package__` will cease to be set or
14-
take into consideration by the import system or standard library. (:gh:`97879`)
13+
is deprecated. In Python 3.15, :attr:`!__package__` will cease to be set by
14+
the import system or standard library. (:gh:`97879`)
1515

1616
* :mod:`ctypes`:
1717

Doc/howto/gdb_helpers.rst

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ enabled::
136136
at Objects/unicodeobject.c:551
137137
#7 0x0000000000440d94 in PyUnicodeUCS2_FromString (u=0x5c2b8d "__lltrace__") at Objects/unicodeobject.c:569
138138
#8 0x0000000000584abd in PyDict_GetItemString (v=
139-
{'Yuck': <type at remote 0xad4730>, '__builtins__': <module at remote 0x7ffff7fd5ee8>, '__file__': 'Lib/test/crashers/nasty_eq_vs_dict.py', '__package__': None, 'y': <Yuck(i=0) at remote 0xaacd80>, 'dict': {0: 0, 1: 1, 2: 2, 3: 3}, '__cached__': None, '__name__': '__main__', 'z': <Yuck(i=0) at remote 0xaace60>, '__doc__': None}, key=
139+
{'Yuck': <type at remote 0xad4730>, '__builtins__': <module at remote 0x7ffff7fd5ee8>, '__file__': 'Lib/test/crashers/nasty_eq_vs_dict.py', 'y': <Yuck(i=0) at remote 0xaacd80>, 'dict': {0: 0, 1: 1, 2: 2, 3: 3}, '__cached__': None, '__name__': '__main__', 'z': <Yuck(i=0) at remote 0xaace60>, '__doc__': None}, key=
140140
0x5c2b8d "__lltrace__") at Objects/dictobject.c:2171
141141

142142
Notice how the dictionary argument to ``PyDict_GetItemString`` is displayed
@@ -148,8 +148,7 @@ cast the value to a pointer of the appropriate type. For example::
148148

149149
(gdb) p globals
150150
$1 = {'__builtins__': <module at remote 0x7ffff7fb1868>, '__name__':
151-
'__main__', 'ctypes': <module at remote 0x7ffff7f14360>, '__doc__': None,
152-
'__package__': None}
151+
'__main__', 'ctypes': <module at remote 0x7ffff7f14360>, '__doc__': None}
153152

154153
(gdb) p *(PyDictObject*)globals
155154
$2 = {ob_refcnt = 3, ob_type = 0x3dbdf85820, ma_fill = 5, ma_used = 5,
@@ -162,8 +161,7 @@ cast the value to a pointer of the appropriate type. For example::
162161
{me_hash = -9177857982131165996, me_key = 'ctypes',
163162
me_value = <module at remote 0x7ffff7f14360>},
164163
{me_hash = -8518757509529533123, me_key = '__doc__', me_value = None},
165-
{me_hash = 0, me_key = 0x0, me_value = 0x0}, {
166-
me_hash = 6614918939584953775, me_key = '__package__', me_value = None}}}
164+
{me_hash = 0, me_key = 0x0, me_value = 0x0}}}
167165

168166
Note that the pretty-printers do not actually call ``repr()``.
169167
For basic types, they try to match its result closely.

Doc/library/importlib.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,6 @@ ABC hierarchy::
367367
- :attr:`module.__file__`
368368
- :attr:`module.__cached__` *(deprecated)*
369369
- :attr:`module.__path__`
370-
- :attr:`module.__package__` *(deprecated)*
371370
- :attr:`module.__loader__` *(deprecated)*
372371

373372
When :meth:`exec_module` is available then backwards-compatible
@@ -1271,7 +1270,8 @@ find and load modules.
12711270

12721271
(Read-only) The fully qualified name of the package the module is in (or the
12731272
empty string for a top-level module).
1274-
See :attr:`module.__package__`.
1273+
See :attr:`module.__package__` for an optional way to override using
1274+
this attribute by the import system.
12751275
If the module is a package then this is the same as :attr:`name`.
12761276

12771277
.. attribute:: has_location

Doc/library/runpy.rst

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ The :mod:`runpy` module provides two functions:
5050
overridden by :func:`run_module`.
5151

5252
The special global variables ``__name__``, ``__spec__``, ``__file__``,
53-
``__cached__``, ``__loader__`` and ``__package__`` are set in the globals
54-
dictionary before the module code is executed. (Note that this is a
55-
minimal set of variables - other variables may be set implicitly as an
56-
interpreter implementation detail.)
53+
``__cached__``, and ``__loader__`` are set in the globals dictionary before
54+
the module code is executed. (Note that this is a minimal set of variables -
55+
other variables may be set implicitly as an interpreter implementation
56+
detail.)
5757

5858
``__name__`` is set to *run_name* if this optional argument is not
5959
:const:`None`, to ``mod_name + '.__main__'`` if the named module is a
@@ -63,7 +63,7 @@ The :mod:`runpy` module provides two functions:
6363
module (that is, ``__spec__.name`` will always be *mod_name* or
6464
``mod_name + '.__main__'``, never *run_name*).
6565

66-
``__file__``, ``__cached__``, ``__loader__`` and ``__package__`` are
66+
``__file__``, ``__cached__``, and ``__loader__`` are
6767
:ref:`set as normal <import-mod-attrs>` based on the module spec.
6868

6969
If the argument *alter_sys* is supplied and evaluates to :const:`True`,
@@ -98,6 +98,9 @@ The :mod:`runpy` module provides two functions:
9898
``__package__`` are deprecated. See
9999
:class:`~importlib.machinery.ModuleSpec` for alternatives.
100100

101+
.. versionchanged:: 3.15
102+
``__package__`` is no longer set.
103+
101104
.. function:: run_path(path_name, init_globals=None, run_name=None)
102105

103106
.. index::
@@ -125,23 +128,23 @@ The :mod:`runpy` module provides two functions:
125128
overridden by :func:`run_path`.
126129

127130
The special global variables ``__name__``, ``__spec__``, ``__file__``,
128-
``__cached__``, ``__loader__`` and ``__package__`` are set in the globals
129-
dictionary before the module code is executed. (Note that this is a
130-
minimal set of variables - other variables may be set implicitly as an
131-
interpreter implementation detail.)
131+
``__cached__``, and ``__loader__`` are set in the globals dictionary before
132+
the module code is executed. (Note that this is a minimal set of variables -
133+
other variables may be set implicitly as an interpreter implementation
134+
detail.)
132135

133136
``__name__`` is set to *run_name* if this optional argument is not
134137
:const:`None` and to ``'<run_path>'`` otherwise.
135138

136139
If *file_path* directly references a script file (whether as source
137140
or as precompiled byte code), then ``__file__`` will be set to
138-
*file_path*, and ``__spec__``, ``__cached__``, ``__loader__`` and
139-
``__package__`` will all be set to :const:`None`.
141+
*file_path*, and ``__spec__``, ``__cached__``, and ``__loader__`` will all
142+
be set to :const:`None`.
140143

141144
If *file_path* is a reference to a valid :data:`sys.path` entry, then
142145
``__spec__`` will be set appropriately for the imported :mod:`__main__`
143146
module (that is, ``__spec__.name`` will always be ``__main__``).
144-
``__file__``, ``__cached__``, ``__loader__`` and ``__package__`` will be
147+
``__file__``, ``__cached__``, and ``__loader__`` will be
145148
:ref:`set as normal <import-mod-attrs>` based on the module spec.
146149

147150
A number of alterations are also made to the :mod:`sys` module. Firstly,
@@ -173,6 +176,9 @@ The :mod:`runpy` module provides two functions:
173176
The setting of ``__cached__``, ``__loader__``, and
174177
``__package__`` are deprecated.
175178

179+
.. versionchanged:: 3.15
180+
``__package__`` is no longer set.
181+
176182
.. seealso::
177183

178184
:pep:`338` -- Executing modules as scripts

Doc/reference/datamodel.rst

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -960,25 +960,21 @@ this approach.
960960

961961
.. attribute:: module.__package__
962962

963-
The :term:`package` a module belongs to.
963+
An optional attribute that states what :term:`package` a module belongs to.
964964

965965
If the module is top-level (that is, not a part of any specific package)
966966
then the attribute should be set to ``''`` (the empty string). Otherwise,
967967
it should be set to the name of the module's package (which can be equal to
968968
:attr:`module.__name__` if the module itself is a package). See :pep:`366`
969969
for further details.
970970

971-
This attribute is used instead of :attr:`~module.__name__` to calculate
972-
explicit relative imports for main modules. It defaults to ``None`` for
973-
modules created dynamically using the :class:`types.ModuleType` constructor;
974-
use :func:`importlib.util.module_from_spec` instead to ensure the attribute
975-
is set to a :class:`str`.
971+
When set, this attribute is used instead of :attr:`~module.__spec__` or
972+
:attr:`~module.__name__` to calculate explicit relative imports for main
973+
modules.
976974

977975
It is **strongly** recommended that you use
978976
:attr:`module.__spec__.parent <importlib.machinery.ModuleSpec.parent>`
979-
instead of :attr:`!module.__package__`. :attr:`__package__` is now only used
980-
as a fallback if :attr:`!__spec__.parent` is not set, and this fallback
981-
path is deprecated.
977+
instead of :attr:`!module.__package__`.
982978

983979
.. versionchanged:: 3.4
984980
This attribute now defaults to ``None`` for modules created dynamically
@@ -1001,8 +997,7 @@ this approach.
1001997
falling back to :attr:`!__package__` during import resolution.
1002998

1003999
.. deprecated-removed:: 3.13 3.15
1004-
:attr:`!__package__` will cease to be set or taken into consideration
1005-
by the import system or standard library.
1000+
:attr:`!__package__` is no longer set.
10061001

10071002
.. attribute:: module.__loader__
10081003

Doc/tutorial/inputoutput.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ This is particularly useful in combination with the built-in function
217217
>>> table = {k: str(v) for k, v in vars().items()}
218218
>>> message = " ".join([f'{k}: ' + '{' + k +'};' for k in table.keys()])
219219
>>> print(message.format(**table))
220-
__name__: __main__; __doc__: None; __package__: None; __loader__: ...
220+
__name__: __main__; __doc__: None; __loader__: ...
221221

222222
As an example, the following lines produce a tidily aligned
223223
set of columns giving integers and their squares and cubes::

Doc/tutorial/modules.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,7 @@ defines. It returns a sorted list of strings::
316316
['__name__', 'fib', 'fib2']
317317
>>> dir(sys) # doctest: +NORMALIZE_WHITESPACE
318318
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
319-
'__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
319+
'__interactivehook__', '__loader__', '__name__', '__spec__',
320320
'__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
321321
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
322322
'_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
@@ -373,7 +373,7 @@ want a list of those, they are defined in the standard module
373373
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
374374
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
375375
'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
376-
'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
376+
'__debug__', '__doc__', '__import__', '__name__', 'abs',
377377
'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
378378
'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
379379
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',

Lib/_pyrepl/_module_completer.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929

3030

3131
def make_default_module_completer() -> ModuleCompleter:
32-
# Inside pyrepl, __package__ is set to None by default
33-
return ModuleCompleter(namespace={'__package__': None})
32+
return ModuleCompleter()
3433

3534

3635
class ModuleCompleter:
@@ -102,7 +101,9 @@ def _find_modules(self, path: str, prefix: str) -> list[str]:
102101

103102
if path.startswith('.'):
104103
# Convert relative path to absolute path
105-
package = self.namespace.get('__package__', '')
104+
if not (package := self.namespace.get('__package__', '')):
105+
if spec := self.namespace.get('__spec__'):
106+
package = spec.parent or ''
106107
path = self.resolve_relative_name(path, package) # type: ignore[assignment]
107108
if path is None:
108109
return []

0 commit comments

Comments
 (0)