Skip to content

Commit

Permalink
gh-82874: Convert remaining importlib format uses to f-str. (#98005)
Browse files Browse the repository at this point in the history
f-yes
  • Loading branch information
gpshead committed Oct 7, 2022
1 parent fa2d43e commit 27369ef
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 28 deletions.
18 changes: 7 additions & 11 deletions Lib/importlib/__init__.py
Expand Up @@ -84,22 +84,21 @@ def find_loader(name, path=None):
try:
loader = sys.modules[name].__loader__
if loader is None:
raise ValueError('{}.__loader__ is None'.format(name))
raise ValueError(f'{name}.__loader__ is None')
else:
return loader
except KeyError:
pass
except AttributeError:
raise ValueError('{}.__loader__ is not set'.format(name)) from None
raise ValueError(f'{name}.__loader__ is not set') from None

spec = _bootstrap._find_spec(name, path)
# We won't worry about malformed specs (missing attributes).
if spec is None:
return None
if spec.loader is None:
if spec.submodule_search_locations is None:
raise ImportError('spec for {} missing loader'.format(name),
name=name)
raise ImportError(f'spec for {name} missing loader', name=name)
raise ImportError('namespace packages do not have loaders',
name=name)
return spec.loader
Expand All @@ -116,9 +115,8 @@ def import_module(name, package=None):
level = 0
if name.startswith('.'):
if not package:
msg = ("the 'package' argument is required to perform a relative "
"import for {!r}")
raise TypeError(msg.format(name))
raise TypeError("the 'package' argument is required to perform a "
f"relative import for {name!r}")
for character in name:
if character != '.':
break
Expand All @@ -144,8 +142,7 @@ def reload(module):
raise TypeError("reload() argument must be a module")

if sys.modules.get(name) is not module:
msg = "module {} not in sys.modules"
raise ImportError(msg.format(name), name=name)
raise ImportError(f"module {name} not in sys.modules", name=name)
if name in _RELOADING:
return _RELOADING[name]
_RELOADING[name] = module
Expand All @@ -155,8 +152,7 @@ def reload(module):
try:
parent = sys.modules[parent_name]
except KeyError:
msg = "parent {!r} not in sys.modules"
raise ImportError(msg.format(parent_name),
raise ImportError(f"parent {parent_name!r} not in sys.modules",
name=parent_name) from None
else:
pkgpath = parent.__path__
Expand Down
22 changes: 11 additions & 11 deletions Lib/importlib/_bootstrap_external.py
Expand Up @@ -197,7 +197,7 @@ def _write_atomic(path, data, mode=0o666):
Be prepared to handle a FileExistsError if concurrent writing of the
temporary file is attempted."""
# id() is used to generate a pseudo-random filename.
path_tmp = '{}.{}'.format(path, id(path))
path_tmp = f'{path}.{id(path)}'
fd = _os.open(path_tmp,
_os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
try:
Expand Down Expand Up @@ -492,8 +492,8 @@ def cache_from_source(path, debug_override=None, *, optimization=None):
optimization = str(optimization)
if optimization != '':
if not optimization.isalnum():
raise ValueError('{!r} is not alphanumeric'.format(optimization))
almost_filename = '{}.{}{}'.format(almost_filename, _OPT, optimization)
raise ValueError(f'{optimization!r} is not alphanumeric')
almost_filename = f'{almost_filename}.{_OPT}{optimization}'
filename = almost_filename + BYTECODE_SUFFIXES[0]
if sys.pycache_prefix is not None:
# We need an absolute path to the py file to avoid the possibility of
Expand Down Expand Up @@ -651,8 +651,8 @@ def _find_module_shim(self, fullname):
# return None.
loader, portions = self.find_loader(fullname)
if loader is None and len(portions):
msg = 'Not importing directory {}: missing __init__'
_warnings.warn(msg.format(portions[0]), ImportWarning)
msg = f'Not importing directory {portions[0]}: missing __init__'
_warnings.warn(msg, ImportWarning)
return loader


Expand Down Expand Up @@ -750,7 +750,7 @@ def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
_imp._fix_co_filename(code, source_path)
return code
else:
raise ImportError('Non-code object in {!r}'.format(bytecode_path),
raise ImportError(f'Non-code object in {bytecode_path!r}',
name=name, path=bytecode_path)


Expand Down Expand Up @@ -951,8 +951,8 @@ def exec_module(self, module):
"""Execute the module."""
code = self.get_code(module.__name__)
if code is None:
raise ImportError('cannot load module {!r} when get_code() '
'returns None'.format(module.__name__))
raise ImportError(f'cannot load module {module.__name__!r} when '
'get_code() returns None')
_bootstrap._call_with_frames_removed(exec, code, module.__dict__)

def load_module(self, fullname):
Expand Down Expand Up @@ -1337,7 +1337,7 @@ def __len__(self):
return len(self._recalculate())

def __repr__(self):
return '_NamespacePath({!r})'.format(self._path)
return f'_NamespacePath({self._path!r})'

def __contains__(self, item):
return item in self._recalculate()
Expand Down Expand Up @@ -1678,7 +1678,7 @@ def _fill_cache(self):
for item in contents:
name, dot, suffix = item.partition('.')
if dot:
new_name = '{}.{}'.format(name, suffix.lower())
new_name = f'{name}.{suffix.lower()}'
else:
new_name = name
lower_suffix_contents.add(new_name)
Expand All @@ -1705,7 +1705,7 @@ def path_hook_for_FileFinder(path):
return path_hook_for_FileFinder

def __repr__(self):
return 'FileFinder({!r})'.format(self.path)
return f'FileFinder({self.path!r})'


# Import setup ###############################################################
Expand Down
2 changes: 1 addition & 1 deletion Lib/importlib/resources/_adapters.py
Expand Up @@ -35,7 +35,7 @@ def _io_wrapper(file, mode='r', *args, **kwargs):
elif mode == 'rb':
return file
raise ValueError(
"Invalid mode value '{}', only 'r' and 'rb' are supported".format(mode)
f"Invalid mode value '{mode}', only 'r' and 'rb' are supported"
)


Expand Down
8 changes: 4 additions & 4 deletions Lib/importlib/util.py
Expand Up @@ -60,10 +60,10 @@ def _find_spec_from_path(name, path=None):
try:
spec = module.__spec__
except AttributeError:
raise ValueError('{}.__spec__ is not set'.format(name)) from None
raise ValueError(f'{name}.__spec__ is not set') from None
else:
if spec is None:
raise ValueError('{}.__spec__ is None'.format(name))
raise ValueError(f'{name}.__spec__ is None')
return spec


Expand Down Expand Up @@ -105,10 +105,10 @@ def find_spec(name, package=None):
try:
spec = module.__spec__
except AttributeError:
raise ValueError('{}.__spec__ is not set'.format(name)) from None
raise ValueError(f'{name}.__spec__ is not set') from None
else:
if spec is None:
raise ValueError('{}.__spec__ is None'.format(name))
raise ValueError(f'{name}.__spec__ is None')
return spec


Expand Down
@@ -1 +1 @@
importlib now uses f-strings internally instead of str.format().
:mod:`importlib` now uses f-strings internally instead of ``str.format``.

0 comments on commit 27369ef

Please sign in to comment.