Use features new to Python 3.8, apply positional-only args

(the latter constitutes a breaking change for MkDocs, but nobody should be relying on these as named args)
This commit is contained in:
Oleh Prypin
2023-10-02 16:34:42 +02:00
parent e2a9576b24
commit 0d8d1f2b4d
8 changed files with 14 additions and 21 deletions

View File

@@ -353,8 +353,7 @@ def build(
# Run `post_build` plugin events.
config.plugins.on_post_build(config=config)
counts = warning_counter.get_counts()
if counts:
if counts := warning_counter.get_counts():
msg = ', '.join(f'{v} {k.lower()}s' for k, v in counts)
raise Abort(f'Aborted with {msg} in strict mode!')

View File

@@ -51,7 +51,7 @@ class BaseConfigOption(Generic[T]):
def default(self, value):
self._default = value
def validate(self, value: object) -> T:
def validate(self, value: object, /) -> T:
return self.run_validation(value)
def reset_warnings(self) -> None:
@@ -64,7 +64,7 @@ class BaseConfigOption(Generic[T]):
The pre-validation process method should be implemented by subclasses.
"""
def run_validation(self, value: object):
def run_validation(self, value: object, /):
"""
Perform validation for a value.

View File

@@ -65,7 +65,7 @@ class SubConfig(Generic[SomeConfig], BaseConfigOption[SomeConfig]):
@overload
def __init__(
self: SubConfig[SomeConfig], config_class: type[SomeConfig], *, validate: bool = True
self: SubConfig[SomeConfig], config_class: type[SomeConfig], /, *, validate: bool = True
):
"""Create a sub-config in a type-safe way, using fields defined in a Config subclass."""
@@ -324,14 +324,14 @@ class Type(Generic[T], OptionallyRequired[T]):
"""
@overload
def __init__(self, type_: type[T], length: int | None = None, **kwargs):
def __init__(self, type_: type[T], /, length: int | None = None, **kwargs):
...
@overload
def __init__(self, type_: tuple[type[T], ...], length: int | None = None, **kwargs):
def __init__(self, type_: tuple[type[T], ...], /, length: int | None = None, **kwargs):
...
def __init__(self, type_, length=None, **kwargs) -> None:
def __init__(self, type_, /, length=None, **kwargs) -> None:
super().__init__(**kwargs)
self._type = type_
self.length = length
@@ -700,7 +700,7 @@ class FilesystemObject(Type[str]):
name = 'file or directory'
def __init__(self, exists: bool = False, **kwargs) -> None:
super().__init__(type_=str, **kwargs)
super().__init__(str, **kwargs)
self.exists = exists
self.config_dir: str | None = None

View File

@@ -254,8 +254,7 @@ class LiveReloadServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGISe
path = environ["PATH_INFO"].encode("latin-1").decode("utf-8", "ignore")
if path.startswith("/livereload/"):
m = re.fullmatch(r"/livereload/([0-9]+)/[0-9]+", path)
if m:
if m := re.fullmatch(r"/livereload/([0-9]+)/[0-9]+", path):
epoch = int(m[1])
start_response("200 OK", [("Content-Type", "text/plain")])

View File

@@ -193,8 +193,7 @@ def _data_to_navigation(data, files: Files, config: MkDocsConfig):
for item in data
]
title, path = data if isinstance(data, tuple) else (None, data)
file = files.get_file_from_path(path)
if file:
if file := files.get_file_from_path(path):
if file.inclusion.is_excluded():
log.log(
min(logging.INFO, config.validation.nav.not_found),

View File

@@ -805,8 +805,7 @@ class _TestPreprocessor(markdown.preprocessors.Preprocessor):
def run(self, lines: list[str]) -> list[str]:
for i, line in enumerate(lines):
m = re.search(r'^--8<-- "(.+)"$', line)
if m:
if m := re.search(r'^--8<-- "(.+)"$', line):
try:
lines[i] = Path(self.base_path, m[1]).read_text()
except OSError:

View File

@@ -134,8 +134,7 @@ class Theme(MutableMapping[str, Any]):
log.debug(f"Loaded theme configuration for '{name}' from '{file_path}': {theme_config}")
parent_theme = theme_config.pop('extends', None)
if parent_theme:
if parent_theme := theme_config.pop('extends', None):
themes = utils.get_theme_names()
if parent_theme not in themes:
raise ValidationError(

View File

@@ -62,8 +62,7 @@ def get_data(doc: str) -> tuple[str, dict[str, Any]]:
data = {}
# First try YAML
m = YAML_RE.match(doc)
if m:
if m := YAML_RE.match(doc):
try:
data = yaml.load(m.group(1), SafeLoader)
if isinstance(data, dict):
@@ -83,8 +82,7 @@ def get_data(doc: str) -> tuple[str, dict[str, Any]]:
if line.strip() == '':
break # blank line - done
m1 = META_RE.match(line)
if m1:
if m1 := META_RE.match(line):
key = m1.group('key').lower().strip()
value = m1.group('value').strip()
if key in data: