Skip to content

Commit d925133

Browse files
authored
bpo-43312: Functions returning default and preferred sysconfig schemes (GH-24644)
1 parent 93f4118 commit d925133

File tree

4 files changed

+131
-38
lines changed

4 files changed

+131
-38
lines changed

‎Doc/library/sysconfig.rst‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,43 @@ identifier. Python currently uses eight paths:
107107
:mod:`sysconfig`.
108108

109109

110+
.. function:: get_default_scheme()
111+
112+
Return the default scheme name for the current platform.
113+
114+
.. versionchanged:: 3.10
115+
This function was previously named ``_get_default_scheme()`` and
116+
considered an implementation detail.
117+
118+
119+
.. function:: get_preferred_scheme(key)
120+
121+
Return a preferred scheme name for an installation layout specified by *key*.
122+
123+
*key* must be either ``"prefix"``, ``"home"``, or ``"user"``.
124+
125+
The return value is a scheme name listed in :func:`get_scheme_names`. It
126+
can be passed to :mod:`sysconfig` functions that take a *scheme* argument,
127+
such as :func:`get_paths`.
128+
129+
.. versionadded:: 3.10
130+
131+
132+
.. function:: _get_preferred_schemes()
133+
134+
Return a dict containing preferred scheme names on the current platform.
135+
Python implementers and redistributors may add their preferred schemes to
136+
the ``_INSTALL_SCHEMES`` module-level global value, and modify this function
137+
to return those scheme names, to e.g. provide different schemes for system
138+
and language package managers to use, so packages installed by either do not
139+
mix with those by the other.
140+
141+
End users should not use this function, but :func:`get_default_scheme` and
142+
:func:`get_preferred_scheme()` instead.
143+
144+
.. versionadded:: 3.10
145+
146+
110147
.. function:: get_path_names()
111148

112149
Return a tuple containing all path names currently supported in

‎Lib/sysconfig.py‎

Lines changed: 57 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def joinuser(*args):
7979

8080
if sys.platform == "darwin" and sys._framework:
8181
return joinuser("~", "Library", sys._framework,
82-
"%d.%d" % sys.version_info[:2])
82+
f"{sys.version_info[0]}.{sys.version_info[1]}")
8383

8484
return joinuser("~", ".local")
8585

@@ -121,8 +121,8 @@ def joinuser(*args):
121121
'scripts', 'data')
122122

123123
_PY_VERSION = sys.version.split()[0]
124-
_PY_VERSION_SHORT = '%d.%d' % sys.version_info[:2]
125-
_PY_VERSION_SHORT_NO_DOT = '%d%d' % sys.version_info[:2]
124+
_PY_VERSION_SHORT = f'{sys.version_info[0]}.{sys.version_info[1]}'
125+
_PY_VERSION_SHORT_NO_DOT = f'{sys.version_info[0]}{sys.version_info[1]}'
126126
_PREFIX = os.path.normpath(sys.prefix)
127127
_BASE_PREFIX = os.path.normpath(sys.base_prefix)
128128
_EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
@@ -189,7 +189,7 @@ def _subst_vars(s, local_vars):
189189
try:
190190
return s.format(**os.environ)
191191
except KeyError:
192-
raise AttributeError('{%s}' % var) from None
192+
raise AttributeError(f'{var}') from None
193193

194194
def _extend_dict(target_dict, other_dict):
195195
target_keys = target_dict.keys()
@@ -212,13 +212,38 @@ def _expand_vars(scheme, vars):
212212
return res
213213

214214

215-
def _get_default_scheme():
216-
if os.name == 'posix':
217-
# the default scheme for posix is posix_prefix
218-
return 'posix_prefix'
219-
return os.name
215+
def _get_preferred_schemes():
216+
if os.name == 'nt':
217+
return {
218+
'prefix': 'nt',
219+
'home': 'posix_home',
220+
'user': 'nt_user',
221+
}
222+
if sys.platform == 'darwin' and sys._framework:
223+
return {
224+
'prefix': 'posix_prefix',
225+
'home': 'posix_home',
226+
'user': 'osx_framework_user',
227+
}
228+
return {
229+
'prefix': 'posix_prefix',
230+
'home': 'posix_home',
231+
'user': 'posix_user',
232+
}
233+
234+
235+
def get_preferred_scheme(key):
236+
scheme = _get_preferred_schemes()[key]
237+
if scheme not in _INSTALL_SCHEMES:
238+
raise ValueError(
239+
f"{key!r} returned {scheme!r}, which is not a valid scheme "
240+
f"on this platform"
241+
)
242+
return scheme
220243

221244

245+
def get_default_scheme():
246+
return get_preferred_scheme('prefix')
222247

223248

224249
def _parse_makefile(filename, vars=None, keep_unresolved=True):
@@ -354,21 +379,20 @@ def get_makefile_filename():
354379
if _PYTHON_BUILD:
355380
return os.path.join(_sys_home or _PROJECT_BASE, "Makefile")
356381
if hasattr(sys, 'abiflags'):
357-
config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags)
382+
config_dir_name = f'config-{_PY_VERSION_SHORT}{sys.abiflags}'
358383
else:
359384
config_dir_name = 'config'
360385
if hasattr(sys.implementation, '_multiarch'):
361-
config_dir_name += '-%s' % sys.implementation._multiarch
386+
config_dir_name += f'-{sys.implementation._multiarch}'
362387
return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
363388

364389

365390
def _get_sysconfigdata_name():
366-
return os.environ.get('_PYTHON_SYSCONFIGDATA_NAME',
367-
'_sysconfigdata_{abi}_{platform}_{multiarch}'.format(
368-
abi=sys.abiflags,
369-
platform=sys.platform,
370-
multiarch=getattr(sys.implementation, '_multiarch', ''),
371-
))
391+
multiarch = getattr(sys.implementation, '_multiarch', '')
392+
return os.environ.get(
393+
'_PYTHON_SYSCONFIGDATA_NAME',
394+
f'_sysconfigdata_{sys.abiflags}_{sys.platform}_{multiarch}',
395+
)
372396

373397

374398
def _generate_posix_vars():
@@ -380,19 +404,19 @@ def _generate_posix_vars():
380404
try:
381405
_parse_makefile(makefile, vars)
382406
except OSError as e:
383-
msg = "invalid Python installation: unable to open %s" % makefile
407+
msg = f"invalid Python installation: unable to open {makefile}"
384408
if hasattr(e, "strerror"):
385-
msg = msg + " (%s)" % e.strerror
409+
msg = f"{msg} ({e.strerror})"
386410
raise OSError(msg)
387411
# load the installed pyconfig.h:
388412
config_h = get_config_h_filename()
389413
try:
390414
with open(config_h, encoding="utf-8") as f:
391415
parse_config_h(f, vars)
392416
except OSError as e:
393-
msg = "invalid Python installation: unable to open %s" % config_h
417+
msg = f"invalid Python installation: unable to open {config_h}"
394418
if hasattr(e, "strerror"):
395-
msg = msg + " (%s)" % e.strerror
419+
msg = f"{msg} ({e.strerror})"
396420
raise OSError(msg)
397421
# On AIX, there are wrong paths to the linker scripts in the Makefile
398422
# -- these paths are relative to the Python source, but when installed
@@ -418,7 +442,7 @@ def _generate_posix_vars():
418442
module.build_time_vars = vars
419443
sys.modules[name] = module
420444

421-
pybuilddir = 'build/lib.%s-%s' % (get_platform(), _PY_VERSION_SHORT)
445+
pybuilddir = f'build/lib.{get_platform()}-{_PY_VERSION_SHORT}'
422446
if hasattr(sys, "gettotalrefcount"):
423447
pybuilddir += '-pydebug'
424448
os.makedirs(pybuilddir, exist_ok=True)
@@ -516,7 +540,7 @@ def get_path_names():
516540
return _SCHEME_KEYS
517541

518542

519-
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
543+
def get_paths(scheme=get_default_scheme(), vars=None, expand=True):
520544
"""Return a mapping containing an install scheme.
521545
522546
``scheme`` is the install scheme name. If not provided, it will
@@ -528,7 +552,7 @@ def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
528552
return _INSTALL_SCHEMES[scheme]
529553

530554

531-
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
555+
def get_path(name, scheme=get_default_scheme(), vars=None, expand=True):
532556
"""Return a path corresponding to the scheme.
533557
534558
``scheme`` is the install scheme name.
@@ -682,16 +706,16 @@ def get_platform():
682706
# At least on Linux/Intel, 'machine' is the processor --
683707
# i386, etc.
684708
# XXX what about Alpha, SPARC, etc?
685-
return "%s-%s" % (osname, machine)
709+
return f"{osname}-{machine}"
686710
elif osname[:5] == "sunos":
687711
if release[0] >= "5": # SunOS 5 == Solaris 2
688712
osname = "solaris"
689-
release = "%d.%s" % (int(release[0]) - 3, release[2:])
713+
release = f"{int(release[0]) - 3}.{release[2:]}"
690714
# We can't use "platform.architecture()[0]" because a
691715
# bootstrap problem. We use a dict to get an error
692716
# if some suspicious happens.
693717
bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
694-
machine += ".%s" % bitness[sys.maxsize]
718+
machine += f".{bitness[sys.maxsize]}"
695719
# fall through to standard osname-release-machine representation
696720
elif osname[:3] == "aix":
697721
from _aix_support import aix_platform
@@ -709,7 +733,7 @@ def get_platform():
709733
get_config_vars(),
710734
osname, release, machine)
711735

712-
return "%s-%s-%s" % (osname, release, machine)
736+
return f"{osname}-{release}-{machine}"
713737

714738

715739
def get_python_version():
@@ -745,18 +769,18 @@ def expand_makefile_vars(s, vars):
745769
def _print_dict(title, data):
746770
for index, (key, value) in enumerate(sorted(data.items())):
747771
if index == 0:
748-
print('%s: ' % (title))
749-
print('\t%s = "%s"' % (key, value))
772+
print(f'{title}: ')
773+
print(f'\t{key} = "{value}"')
750774

751775

752776
def _main():
753777
"""Display all information sysconfig detains."""
754778
if '--generate-posix-vars' in sys.argv:
755779
_generate_posix_vars()
756780
return
757-
print('Platform: "%s"' % get_platform())
758-
print('Python version: "%s"' % get_python_version())
759-
print('Current installation scheme: "%s"' % _get_default_scheme())
781+
print(f'Platform: "{get_platform()}"')
782+
print(f'Python version: "{get_python_version()}"')
783+
print(f'Current installation scheme: "{get_default_scheme()}"')
760784
print()
761785
_print_dict('Paths', get_paths())
762786
print()

‎Lib/test/test_sysconfig.py‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
import sysconfig
1515
from sysconfig import (get_paths, get_platform, get_config_vars,
1616
get_path, get_path_names, _INSTALL_SCHEMES,
17-
_get_default_scheme, _expand_vars,
18-
get_scheme_names, get_config_var, _main)
17+
get_default_scheme, get_scheme_names, get_config_var,
18+
_expand_vars, _get_preferred_schemes, _main)
1919
import _osx_support
2020

2121

@@ -94,17 +94,46 @@ def test_get_path_names(self):
9494

9595
def test_get_paths(self):
9696
scheme = get_paths()
97-
default_scheme = _get_default_scheme()
97+
default_scheme = get_default_scheme()
9898
wanted = _expand_vars(default_scheme, None)
9999
wanted = sorted(wanted.items())
100100
scheme = sorted(scheme.items())
101101
self.assertEqual(scheme, wanted)
102102

103103
def test_get_path(self):
104-
# XXX make real tests here
104+
config_vars = get_config_vars()
105105
for scheme in _INSTALL_SCHEMES:
106106
for name in _INSTALL_SCHEMES[scheme]:
107-
res = get_path(name, scheme)
107+
expected = _INSTALL_SCHEMES[scheme][name].format(**config_vars)
108+
self.assertEqual(
109+
os.path.normpath(get_path(name, scheme)),
110+
os.path.normpath(expected),
111+
)
112+
113+
def test_get_default_scheme(self):
114+
self.assertIn(get_default_scheme(), _INSTALL_SCHEMES)
115+
116+
def test_get_preferred_schemes(self):
117+
expected_schemes = {'prefix', 'home', 'user'}
118+
119+
# Windows.
120+
os.name = 'nt'
121+
schemes = _get_preferred_schemes()
122+
self.assertIsInstance(schemes, dict)
123+
self.assertEqual(set(schemes), expected_schemes)
124+
125+
# Mac and Linux, shared library build.
126+
os.name = 'posix'
127+
schemes = _get_preferred_schemes()
128+
self.assertIsInstance(schemes, dict)
129+
self.assertEqual(set(schemes), expected_schemes)
130+
131+
# Mac, framework build.
132+
os.name = 'posix'
133+
sys.platform = 'darwin'
134+
sys._framework = True
135+
self.assertIsInstance(schemes, dict)
136+
self.assertEqual(set(schemes), expected_schemes)
108137

109138
def test_get_config_vars(self):
110139
cvars = get_config_vars()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
New functions :func:`sysconfig.get_preferred_scheme` and
2+
:func:`sysconfig.get_default_scheme` are added to query a platform for its
3+
preferred "user", "home", and "prefix" (default) scheme names.

0 commit comments

Comments
 (0)