Skip to content

Commit f7ab7c4

Browse files
[3.15] gh-149671: Restore compatibility with setuptools -nspkg.pth files in site module (GH-151319) (#151489)
gh-149671: Restore compatibility with setuptools -nspkg.pth files in site module (GH-151319) Inject the "sitedir" variable in the frame which executes ".pth" code. (cherry picked from commit 18f3ffe) Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent 1b457d3 commit f7ab7c4

3 files changed

Lines changed: 22 additions & 0 deletions

File tree

Lib/site.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,11 @@ def _exec_imports(self):
505505
# batch. In that case, PEP 829 says the import lines are
506506
# suppressed in favor of the .start's entry points.
507507
for filename, imports in self._importexecs.items():
508+
# Inject 'sitedir' local variable in the current frame for
509+
# compatibility with Python 3.14. Especially, "-nspkg.pth" files
510+
# generated by setuptools use: sys._getframe(1).f_locals['sitedir'].
511+
sitedir = os.path.dirname(filename)
512+
508513
# Given "/path/to/foo.pth", check whether "/path/to/foo.start" was
509514
# registered in this same batch.
510515
name, dot, pth = filename.rpartition(".")

Lib/test/test_site.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,20 @@ def test_addsitedir_hidden_file_attribute(self):
233233
self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
234234
self.assertIn(pth_file.base_dir, sys.path)
235235

236+
def test_sitedir_variable(self):
237+
# gh-149671: setuptools use of `-nspkg.pth` files in Python < 3.15.
238+
code = '; '.join((
239+
# Code used by "-nspkg.pth" files generated by setuptools.
240+
"import sys",
241+
"sitedir = sys._getframe(1).f_locals['sitedir']",
242+
"print(sitedir)",
243+
))
244+
pth_dir, pth_fn = self.make_pth(code)
245+
with support.captured_stdout() as stdout:
246+
known_paths = site.addpackage(pth_dir, pth_fn, set())
247+
sitedir = stdout.getvalue().rstrip()
248+
self.assertEqual(sitedir, pth_dir)
249+
236250
# This tests _getuserbase, hence the double underline
237251
# to distinguish from a test for getuserbase
238252
def test__getuserbase(self):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Restore compatibility with setuptools ``-nspkg.pth`` files in the :mod:`site`
2+
module. Inject ``sitedir`` variable in the frame which executes pth code.
3+
Patch by Victor Stinner.

0 commit comments

Comments
 (0)