Skip to content

Commit baf3974

Browse files
committed
chore: black
1 parent 9b83899 commit baf3974

26 files changed

+164
-99
lines changed

mininterface/_lib/argparse_support.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
11
import re
22
import sys
3-
from argparse import (SUPPRESS, Action, ArgumentParser, _AppendAction,
4-
_AppendConstAction, _CountAction, _HelpAction,
5-
_StoreConstAction, _StoreFalseAction, _StoreTrueAction,
6-
_SubParsersAction, _VersionAction)
3+
from argparse import (
4+
SUPPRESS,
5+
Action,
6+
ArgumentParser,
7+
_AppendAction,
8+
_AppendConstAction,
9+
_CountAction,
10+
_HelpAction,
11+
_StoreConstAction,
12+
_StoreFalseAction,
13+
_StoreTrueAction,
14+
_SubParsersAction,
15+
_VersionAction,
16+
)
717
from collections import defaultdict
818
from dataclasses import MISSING, Field, dataclass, field, make_dataclass
919
from functools import cached_property
@@ -65,7 +75,9 @@ def has_property(self):
6575
return self.action.dest in self.properties
6676

6777

68-
def parser_to_dataclass(parser: ArgumentParser, name: str = "Args") -> tuple[DataClass | list[DataClass], Optional[str]]:
78+
def parser_to_dataclass(
79+
parser: ArgumentParser, name: str = "Args"
80+
) -> tuple[DataClass | list[DataClass], Optional[str]]:
6981
"""
7082
Note: Ex. parser.add_argument("--time", type=time) -> does work at all in argparse, here it works.
7183
@@ -197,8 +209,9 @@ def _make_dataclass_from_actions(
197209
if action.choices:
198210
# With the drop of Python 3.10, use mere:
199211
# arg_type = Literal[*action.choices]
200-
if sys.version_info >= (3,11):
212+
if sys.version_info >= (3, 11):
201213
from .future_compatibility import literal
214+
202215
arg_type = literal(action.choices)
203216
else:
204217
# we do not prefer this option as tyro does not understand it

mininterface/_lib/auxiliary.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55
from dataclasses import fields, is_dataclass
66
from functools import lru_cache
77
from types import UnionType
8-
from typing import (Any, Callable, Iterable, Optional, TypeVar, Union, Literal,
9-
get_args, get_origin, get_type_hints)
8+
from typing import Any, Callable, Iterable, Optional, TypeVar, Union, Literal, get_args, get_origin, get_type_hints
109

1110
from annotated_types import Ge, Gt, Le, Len, Lt, MultipleOf
1211

@@ -75,7 +74,9 @@ def get_descriptions(parser: ArgumentParser) -> dict:
7574
"""Load descriptions from the parser. Strip argparse info about the default value as it will be editable in the form."""
7675
# clean-up tyro stuff that may have a meaning in the CLI, but not in the UI
7776
return {
78-
re.sub(r"\s\(positional\)$", "", action.dest).replace("-", "_"): re.sub(r"\((default|fixed to|required).*\)", "", action.help or "")
77+
re.sub(r"\s\(positional\)$", "", action.dest).replace("-", "_"): re.sub(
78+
r"\((default|fixed to|required).*\)", "", action.help or ""
79+
)
7980
for action in parser._actions
8081
}
8182

@@ -201,7 +202,7 @@ def matches_annotation(value, annotation) -> bool:
201202
if origin is list:
202203
return all(matches_annotation(item, subtypes[0]) for item in value)
203204
elif origin is tuple:
204-
if len(subtypes) == 2 and subtypes[1] is Ellipsis: # ex. tuple[int, ...]
205+
if len(subtypes) == 2 and subtypes[1] is Ellipsis: # ex. tuple[int, ...]
205206
return all(matches_annotation(v, subtypes[0]) for v in value)
206207
if len(subtypes) != len(value):
207208
return False
@@ -286,8 +287,9 @@ def merge_dicts(d1: dict, d2: dict):
286287
d1[key] = value
287288
return d1
288289

290+
289291
def dict_diff(a: dict, b: dict) -> dict:
290-
""" Returns the B values where they differ. """
292+
"""Returns the B values where they differ."""
291293
result = {}
292294
for k in b:
293295
if isinstance(a.get(k), dict) and isinstance(b.get(k), dict):
@@ -298,6 +300,7 @@ def dict_diff(a: dict, b: dict) -> dict:
298300
result[k] = b[k]
299301
return result
300302

303+
301304
def naturalsize(value: float | str, *args) -> str:
302305
"""For a bare interface, humanize might not be installed."""
303306
if naturalsize_:
@@ -346,6 +349,7 @@ def allows_none(annotation) -> bool:
346349
return any(arg is type(None) for arg in args)
347350
return False
348351

352+
349353
def strip_none(annotation):
350354
"""Return the same annotation but without NoneType inside a Union/Optional."""
351355
origin = get_origin(annotation)
@@ -358,7 +362,8 @@ def strip_none(annotation):
358362

359363
return annotation
360364

361-
@lru_cache(maxsize=1024*10)
365+
366+
@lru_cache(maxsize=1024 * 10)
362367
def _get_origin(tp: Any):
363368
"""
364369
Cached version of typing.get_origin.

mininterface/_lib/cli_flags.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def __init__(
3333
case int():
3434
self._add_verbose = True
3535
self.default_verbosity = add_verbose
36-
self._verbosity_sequence = list(range(add_verbose-10, -1, -10))
36+
self._verbosity_sequence = list(range(add_verbose - 10, -1, -10))
3737
case list() | tuple():
3838
self._add_verbose = True
3939
self.default_verbosity = add_verbose[0]
@@ -106,7 +106,7 @@ def get_log_level(self, count):
106106
Returns:
107107
int: log level
108108
"""
109-
if count == -1: # quiet flag
109+
if count == -1: # quiet flag
110110
return logging.ERROR
111111
if not count:
112112
return self.default_verbosity

mininterface/_lib/cli_parser.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,11 @@ def assure_args(args: Optional[Sequence[str]] = None):
7171
args = []
7272
return args
7373

74+
7475
def _subcommands_default_appliable(kwargs, _crawling):
7576
if len(_crawling.get()):
76-
return kwargs.get("subcommands_default")
77+
return kwargs.get("subcommands_default")
78+
7779

7880
def parse_cli(
7981
env_or_list: Type[EnvClass] | list[Type[EnvClass]],
@@ -156,7 +158,6 @@ def annot(type_form):
156158
warn(f"Cannot apply {annotations} on Python <= 3.11.")
157159
return type_form
158160

159-
160161
#
161162
# --- Begin to launch tyro.cli ---
162163
# This will be divided into four sections.
@@ -189,7 +190,9 @@ def annot(type_form):
189190
except BaseException:
190191
# Why this exception handling? Try putting this out and test_strange_error_mitigation fails.
191192
if len(env_classes) > 1 and kwargs.get("default"):
192-
env = cli(annot(kwargs["default"].__class__), args=args[1:], registry=_custom_registry, **kwargs)
193+
env = cli(
194+
annot(kwargs["default"].__class__), args=args[1:], registry=_custom_registry, **kwargs
195+
)
193196
else:
194197
raise
195198
except SystemExit as exception:
@@ -199,13 +202,20 @@ def annot(type_form):
199202
# Help-text exception, continue here and try again with subcommands. As it raises SystemExit first,
200203
# it will raise SystemExit in the second run too.
201204
helponly = True
202-
elif _crawled is None and _subcommands_default_appliable(kwargs, _crawling) and exception.code == 2 and failed_fields.get():
205+
elif (
206+
_crawled is None
207+
and _subcommands_default_appliable(kwargs, _crawling)
208+
and exception.code == 2
209+
and failed_fields.get()
210+
):
203211
# Some fields are missing, directly try again. If it raises again
204212
# (some fields are really missing which cannot be filled from the subcommanded-config),
205213
# it will immediately raise again and trigger the (C) dialog missing section.
206214
# If it worked (and no fields are missing), we continue here without triggering the (C) dialog missing section.
207215
_crawled = True
208-
env, enforce_dialog = _try_with_subcommands(kwargs, m, args, type_form, env_classes, _custom_registry, annot, _req_fields)
216+
env, enforce_dialog = _try_with_subcommands(
217+
kwargs, m, args, type_form, env_classes, _custom_registry, annot, _req_fields
218+
)
209219
else:
210220
# This is either a recurrent call from the (C) dialog missing section (and thus subcommand-config re-parsing was done),
211221
# or there is no subcommand-config data and thus we continue as if this exception handling did not happen.
@@ -220,7 +230,9 @@ def annot(type_form):
220230
if _crawled is None and _subcommands_default_appliable(kwargs, _crawling):
221231
# Why not catching enforce_dialog here? As we are here, calling tyro.cli worked for the first time.
222232
# For sure then, there were no choose_subcommand dialog, subcommands for sure are all written in the CLI.
223-
env, _ = _try_with_subcommands(kwargs, None if helponly else m, args, type_form, env_classes, _custom_registry, annot, _req_fields)
233+
env, _ = _try_with_subcommands(
234+
kwargs, None if helponly else m, args, type_form, env_classes, _custom_registry, annot, _req_fields
235+
)
224236

225237
# Why setting m.env instead of putting into into a constructor of a new get_interface() call?
226238
# 1. Getting the interface is a costly operation
@@ -291,8 +303,9 @@ def annot(type_form):
291303

292304
return env, dialog_raised
293305

306+
294307
def _try_with_subcommands(kwargs, m, args, type_form, env_classes, _custom_registry, annot, _req_fields):
295-
""" This awful method is here to re-parse the tyro.cli with the subcommand-config """
308+
"""This awful method is here to re-parse the tyro.cli with the subcommand-config"""
296309

297310
failed_fields.set([])
298311
old_defs = kwargs.get("default", {})
@@ -306,7 +319,7 @@ def _try_with_subcommands(kwargs, m, args, type_form, env_classes, _custom_regis
306319
if not old_defs:
307320
old_defs = kwargs["subcommands_default_union"][cl_name]
308321
subc = kwargs["subcommands_default"].get(cl_name)
309-
else: # we should never come here
322+
else: # we should never come here
310323
raise ValueError("Subcommands parsing failed")
311324
else:
312325
env = env_classes[0]
@@ -399,7 +412,14 @@ def _dialog_missing(
399412
else:
400413
disk = asdict(dc) if (dc := kwargs.get("default")) else {}
401414
crawled = True
402-
kwargs["default"] = create_with_missing(env_cl, disk, req_fields, m, subc=kwargs.get("subcommands_default"), subc_passage=[cl_name for _, cl_name, _ in _crawling.get()])
415+
kwargs["default"] = create_with_missing(
416+
env_cl,
417+
disk,
418+
req_fields,
419+
m,
420+
subc=kwargs.get("subcommands_default"),
421+
subc_passage=[cl_name for _, cl_name, _ in _crawling.get()],
422+
)
403423

404424
missing_req = _fetch_currently_failed(req_fields)
405425
""" Fields required and missing from CLI """

mininterface/_lib/cli_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,4 +168,4 @@ def run(self): ...
168168
# val: Message | Console
169169
# m = run(Env) # here
170170
# m = run([Message, Console]) # and here too
171-
# Then, add is as a tip to Supported-types.md.
171+
# Then, add is as a tip to Supported-types.md.

mininterface/_lib/dataclass_creation.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737

3838
T = TypeVar("T")
3939

40+
4041
def coerce_type_to_annotation(value, annotation):
4142
"""
4243
Coerce value (e.g. list) to expected type (e.g. tuple[int, int]).
@@ -262,10 +263,12 @@ def _init_struct_value(ftype, disk_value, wf, fname, m, subc, subc_passage, subs
262263
del wf[fname]
263264
return v
264265

266+
265267
def _is_subcommands(ftype):
266268
origin = _get_origin(ftype)
267269
return (origin is Union or origin is UnionType) and all(_is_struct_type(cl) for cl in get_args(ftype))
268270

271+
269272
def _process_field(
270273
fname,
271274
ftype,
@@ -357,19 +360,22 @@ def choose_subcommand(env_classes: list[Type[DataClass]], m: "Mininterface[EnvCl
357360
)
358361
return env
359362

360-
def pop_from_passage(passage, env_classes: Sequence[T])-> tuple[T, str]:
363+
364+
def pop_from_passage(passage, env_classes: Sequence[T]) -> tuple[T, str]:
361365
cl_name = passage.pop(0)
362366
# there might be a subcommand prefix, ex. 'val:message' -> 'message'
363367
cl_name = cl_name.partition(":")[2] or cl_name
364368
ftype = get_chosen(cl_name, env_classes)
365369
return ftype, cl_name
366370

371+
367372
def get_chosen(cl_name, env_classes):
368373
for cl in env_classes:
369374
if to_kebab_case(cl.__name__) == cl_name:
370375
return cl
371376
raise ValueError(f"Type {cl_name} not found in {env_classes}")
372377

378+
373379
def to_kebab_case(name: str) -> str:
374380
"""MyClass -> my-class"""
375381
# I did not find where tyro does it. If I find it, I might use its function instead.

mininterface/_lib/form_dict.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ class Env:
106106

107107

108108
def tagdict_resolve(d: FormDict, extract_main=False, _root=True) -> dict:
109-
""" Returns a new dict when all Tags are replaced with their values.
109+
"""Returns a new dict when all Tags are replaced with their values.
110110
111111
Args:
112112
extract_main: UI need the main section act as nested.
@@ -125,8 +125,9 @@ def tagdict_resolve(d: FormDict, extract_main=False, _root=True) -> dict:
125125
return {**main, **out}
126126
return out
127127

128-
def dict_added_main(data:dict):
129-
""" Gets a dict modified to the same form as a TagDict (adds the main "" section) """
128+
129+
def dict_added_main(data: dict):
130+
"""Gets a dict modified to the same form as a TagDict (adds the main "" section)"""
130131
out = {}
131132
out[""] = {}
132133
for key, val in data.items():
@@ -137,8 +138,9 @@ def dict_added_main(data:dict):
137138

138139
return out
139140

140-
def dict_removed_main(data:dict):
141-
""" Expand the main "" section among other keys. """
141+
142+
def dict_removed_main(data: dict):
143+
"""Expand the main "" section among other keys."""
142144
out = dict(data.get("", {}))
143145

144146
for key, val in data.items():
@@ -149,12 +151,14 @@ def dict_removed_main(data:dict):
149151
out[key] = val
150152
return out
151153

152-
def dict_has_main(data:dict):
154+
155+
def dict_has_main(data: dict):
153156
"""
154157
Calling `m.select(title="")` would raise `m.form({'': SelectTag(...)})`. The tag with the empty name != main section (which is dict).
155158
"""
156159
return isinstance(data.get(""), dict)
157160

161+
158162
def dict_to_tagdict(data: dict, mininterface: Optional["Mininterface"] = None) -> TagDict:
159163
fd = {}
160164
for key, val in data.items():
@@ -234,7 +238,9 @@ def dataclass_to_tagdict(env: EnvClass, mininterface: Optional["Mininterface"] =
234238
raise ValueError(f"We got a namespace instead of class, CLI probably failed: {env}")
235239

236240
for param, val in iterate_attributes(env):
237-
if hasattr(val, "__dict__") and not isinstance(val, (FunctionType, MethodType, MissingTagValue, Enum)): # nested config hierarchy
241+
if hasattr(val, "__dict__") and not isinstance(
242+
val, (FunctionType, MethodType, MissingTagValue, Enum)
243+
): # nested config hierarchy
238244
# nested config hierarchy
239245
# Why checking the isinstance? See Tag._is_a_callable.
240246
subdict[param] = dataclass_to_tagdict(val, mininterface, _nested=True)
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
21
from typing import Annotated, Literal
32

43

54
def literal(c):
65
return Literal[*c]
76

7+
88
def spread_annotated(obj, annotations):
9-
return Annotated[obj, *annotations]
9+
return Annotated[obj, *annotations]

mininterface/_lib/run.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def run(
3434
*,
3535
add_config: bool = False,
3636
add_help: bool = True,
37-
add_verbose: bool|int|Sequence[int] = True,
37+
add_verbose: bool | int | Sequence[int] = True,
3838
add_version: Optional[str] = None,
3939
add_version_package: Optional[str] = None,
4040
add_quiet: bool = False,
@@ -249,7 +249,7 @@ class Env:
249249
args = assure_args(args)
250250

251251
# Prepare the config file
252-
if cf:= environ.get("MININTERFACE_CONFIG"):
252+
if cf := environ.get("MININTERFACE_CONFIG"):
253253
config_file = cf
254254
if add_config and "--config" in args:
255255
# Detect the `--config` and pop it.
@@ -261,7 +261,7 @@ class Env:
261261
except IndexError:
262262
raise ValueError("Missing value after --config")
263263
else:
264-
del args[idx:idx + 2]
264+
del args[idx : idx + 2]
265265
if config_file is True and not kwargs.get("default"):
266266
# Undocumented feature. User put a namespace into kwargs["default"]
267267
# that already serves for defaults. We do not fetch defaults yet from a config file.
@@ -330,9 +330,7 @@ class Env:
330330
# A single Env object, or a list of such objects (with one is not/being selected via args)
331331
# Load configuration from CLI and a config file
332332
try:
333-
parse_cli(
334-
env_or_list, kwargs, m, cf, ask_for_missing, args, ask_on_empty_cli, cliset
335-
)
333+
parse_cli(env_or_list, kwargs, m, cf, ask_for_missing, args, ask_on_empty_cli, cliset)
336334
except Exception as e:
337335
# Undocumented MININTERFACE_DEBUG flag. Note ipdb package requirement.
338336
from ast import literal_eval

0 commit comments

Comments
 (0)