|
26 | 26 | previous_config, |
27 | 27 | ) |
28 | 28 | from ._common import ( |
29 | | - LoggerProperty, |
30 | 29 | debug_mode_active, |
31 | 30 | get_optionals_as_positionals_actions, |
32 | 31 | is_subclasses_disabled, |
|
41 | 40 | ) |
42 | 41 | from ._deprecated import ParserDeprecations, deprecated_skip_check, deprecated_yaml_comments |
43 | 42 | from ._formatters import DefaultHelpFormatter, get_env_var |
44 | | -from ._instantiation import get_class_instantiators |
| 43 | +from ._instantiation import InstantiateMethod |
45 | 44 | from ._jsonnet import ActionJsonnet |
46 | 45 | from ._jsonschema import ActionJsonSchema |
47 | 46 | from ._link_arguments import ActionLink, ArgumentLinking |
|
56 | 55 | Namespace, |
57 | 56 | NSKeyError, |
58 | 57 | get_non_meta_sorted_keys, |
59 | | - get_value_and_parent, |
60 | 58 | is_meta_key, |
61 | 59 | patch_namespace, |
62 | 60 | recreate_branches, |
63 | 61 | remove_meta, |
64 | | - split_key, |
65 | 62 | split_key_leaf, |
66 | 63 | split_key_root, |
67 | 64 | ) |
|
102 | 99 | return_parser_if_captured, |
103 | 100 | ) |
104 | 101 |
|
105 | | -__all__ = ["ArgumentParser", "ActionsContainer"] |
| 102 | +__all__ = ["ArgumentParser"] |
106 | 103 |
|
107 | 104 |
|
108 | 105 | _parse_known_has_intermixed = "intermixed" in inspect.signature(argparse.ArgumentParser._parse_known_args).parameters |
109 | 106 |
|
110 | 107 |
|
111 | | -class ActionsContainer(SignatureArguments, argparse._ActionsContainer): |
| 108 | +class ActionsContainer(ArgumentLinking, InstantiateMethod, SignatureArguments, argparse._ActionsContainer): |
112 | 109 | """Extension of ``argparse._ActionsContainer`` to support additional functionalities.""" |
113 | 110 |
|
114 | 111 | _action_groups: Sequence["ArgumentGroup"] # type: ignore[assignment] |
@@ -229,7 +226,7 @@ class ArgumentGroup(ActionsContainer, argparse._ArgumentGroup): |
229 | 226 | parser: Optional[Union["ArgumentParser", ActionsContainer]] = None |
230 | 227 |
|
231 | 228 |
|
232 | | -class ArgumentParser(ParserDeprecations, ActionsContainer, ArgumentLinking, LoggerProperty, argparse.ArgumentParser): |
| 229 | +class ArgumentParser(ParserDeprecations, ActionsContainer, argparse.ArgumentParser): |
233 | 230 | """Parser for command line, configuration files and environment variables.""" |
234 | 231 |
|
235 | 232 | formatter_class: type[argparse.HelpFormatter] |
@@ -287,10 +284,6 @@ def __init__( |
287 | 284 |
|
288 | 285 | ## Parsing methods ## |
289 | 286 |
|
290 | | - def parse_known_args(self, *args, **kwargs) -> NoReturn: |
291 | | - """Raises ``NotImplementedError``, not supported since typos in configs would go unnoticed.""" |
292 | | - raise NotImplementedError("parse_known_args not supported because typos in configs would go unnoticed.") |
293 | | - |
294 | 287 | def _parse_known_args_internal(self, args=None, namespace=None, *, argcomplete: bool = False): |
295 | 288 | if argcomplete: |
296 | 289 | namespace = get_argcomplete_namespace(self, namespace) |
@@ -716,9 +709,13 @@ def _load_config_parser_mode( |
716 | 709 |
|
717 | 710 | ## Methods for adding to the parser ## |
718 | 711 |
|
719 | | - def add_subparsers(self, *args, **kwargs) -> NoReturn: |
720 | | - """Raises a ``NotImplementedError`` since jsonargparse uses ``add_subcommands``.""" |
721 | | - raise NotImplementedError("In jsonargparse subcommands are added using the add_subcommands method.") |
| 712 | + add_argument = ActionsContainer.add_argument |
| 713 | + add_argument_group = ActionsContainer.add_argument_group |
| 714 | + add_function_arguments = SignatureArguments.add_function_arguments |
| 715 | + add_method_arguments = SignatureArguments.add_method_arguments |
| 716 | + add_class_arguments = SignatureArguments.add_class_arguments |
| 717 | + add_subclass_arguments = SignatureArguments.add_subclass_arguments |
| 718 | + link_arguments = ArgumentLinking.link_arguments |
722 | 719 |
|
723 | 720 | def add_subcommands(self, required: bool = True, dest: str = "subcommand", **kwargs) -> ActionSubCommands: |
724 | 721 | """Adds subcommand parsers to the ArgumentParser. |
@@ -1064,6 +1061,8 @@ def get_defaults(self, skip_validation: bool = False, **kwargs) -> Namespace: |
1064 | 1061 |
|
1065 | 1062 | return cfg |
1066 | 1063 |
|
| 1064 | + set_defaults = ActionsContainer.set_defaults |
| 1065 | + |
1067 | 1066 | ## Completion script methods ## |
1068 | 1067 |
|
1069 | 1068 | def _raise_invalidated_by_completion_script(self, *args, **kwargs) -> NoReturn: |
@@ -1202,94 +1201,7 @@ def check_values(cfg): |
1202 | 1201 | if not skip_required and not lenient_check.get(): |
1203 | 1202 | check_required(cfg, self, prefix) |
1204 | 1203 |
|
1205 | | - def instantiate( |
1206 | | - self, |
1207 | | - cfg: Namespace, |
1208 | | - instantiate_groups: bool = True, |
1209 | | - ) -> Namespace: |
1210 | | - """Instantiates all signature components in a configuration namespace. |
1211 | | -
|
1212 | | - Processes the configuration recursively, converting each signature |
1213 | | - component registered with the parser into its corresponding Python |
1214 | | - object: |
1215 | | -
|
1216 | | - - **Class/subclass type arguments** (``add_argument`` with a class type |
1217 | | - or ``add_class_arguments``/``add_subclass_arguments``): An object with |
1218 | | - ``class_path`` and optionally ``init_args`` is replaced by an instance |
1219 | | - of the referenced class, created by calling |
1220 | | - ``class_type(**init_args)``. For the case of classes with disabled |
1221 | | - subclasses, the namespace can have directly the init args without the |
1222 | | - ``class_path`` + ``init_args`` wrapper. |
1223 | | -
|
1224 | | - - **Callable type arguments**: A dot-import string pointing to a |
1225 | | - function or method is resolved to the callable object. When |
1226 | | - ``class_path``/``init_args`` is given instead and the class |
1227 | | - instantiates into a callable (or is a subclass of the callable's |
1228 | | - return type), the result is either a class instance or — when not all |
1229 | | - call arguments are provided yet — a :func:`functools.partial` bound to |
1230 | | - the given ``init_args``. |
1231 | | -
|
1232 | | - - **Instantiation order**: Components are processed in the order |
1233 | | - determined by argument links applied on instantiation. |
1234 | | -
|
1235 | | - Args: |
1236 | | - cfg: The configuration object to use. Must have been produced by |
1237 | | - one of the ``parse_*`` methods and not modified in a way that |
1238 | | - breaks the structure expected by the parser. |
1239 | | - instantiate_groups: Whether class groups should be instantiated. |
1240 | | -
|
1241 | | - Returns: |
1242 | | - A new configuration object where every registered signature |
1243 | | - component has been replaced by its corresponding Python object. |
1244 | | - """ |
1245 | | - components: list[Union[ActionTypeHint, _ActionConfigLoad, ArgumentGroup]] = [] |
1246 | | - for action in filter_non_parsing_actions(self._actions): |
1247 | | - if isinstance(action, ActionTypeHint): |
1248 | | - components.append(action) |
1249 | | - elif isinstance(action, ActionLink) and isinstance(action.target[1], ActionTypeHint): |
1250 | | - components.append(action.target[1]) |
1251 | | - |
1252 | | - if instantiate_groups: |
1253 | | - skip = {c.dest for c in components} |
1254 | | - groups = [g for g in self._action_groups if hasattr(g, "instantiate_class") and g.dest not in skip] |
1255 | | - components.extend(groups) |
1256 | | - |
1257 | | - components.sort(key=lambda x: -len(split_key(x.dest))) # type: ignore[arg-type] |
1258 | | - order = ActionLink.instantiation_order(self) |
1259 | | - components = ActionLink.reorder(order, components) |
1260 | | - |
1261 | | - cfg = cfg.clone(with_meta=False) |
1262 | | - for component in components: |
1263 | | - ActionLink.apply_instantiation_links(self, cfg, target=component.dest) |
1264 | | - if isinstance(component, ActionTypeHint): |
1265 | | - try: |
1266 | | - value, parent, key = get_value_and_parent(cfg, component.dest) |
1267 | | - except (KeyError, AttributeError): |
1268 | | - pass |
1269 | | - else: |
1270 | | - if value is not None: |
1271 | | - with parser_context( |
1272 | | - parent_parser=self, |
1273 | | - nested_links=ActionLink.get_nested_links(self, component), |
1274 | | - class_instantiators=get_class_instantiators(self), |
1275 | | - applied_instantiation_links=cfg.get("__applied_instantiation_links__"), |
1276 | | - ): |
1277 | | - parent[key] = component.instantiate_classes(value) |
1278 | | - else: |
1279 | | - with parser_context( |
1280 | | - load_value_mode=self.parser_mode, |
1281 | | - class_instantiators=get_class_instantiators(self), |
1282 | | - applied_instantiation_links=cfg.get("__applied_instantiation_links__"), |
1283 | | - ): |
1284 | | - component.instantiate_class(component, cfg) |
1285 | | - |
1286 | | - ActionLink.apply_instantiation_links(self, cfg, order=order) |
1287 | | - |
1288 | | - subcommand, subparser = get_subcommand(self, cfg, fail_no_subcommand=False) |
1289 | | - if subcommand is not None and subparser is not None: |
1290 | | - cfg[subcommand] = subparser.instantiate(cfg[subcommand], instantiate_groups=instantiate_groups) |
1291 | | - |
1292 | | - return cfg |
| 1204 | + instantiate = InstantiateMethod.instantiate |
1293 | 1205 |
|
1294 | 1206 | def strip_unknown(self, cfg: Namespace) -> Namespace: |
1295 | 1207 | """Removes all unknown keys from a configuration object. |
@@ -1623,6 +1535,16 @@ def dump_header(self, dump_header: Optional[list[str]]): |
1623 | 1535 | raise ValueError("Expected dump_header to be None or a list of strings.") |
1624 | 1536 | self._dump_header = dump_header |
1625 | 1537 |
|
| 1538 | + # Not supported methods |
| 1539 | + |
| 1540 | + def parse_known_args(self, *args, **kwargs) -> NoReturn: |
| 1541 | + """Raises ``NotImplementedError`` since typos in configs would go unnoticed.""" |
| 1542 | + raise NotImplementedError("parse_known_args not supported because typos in configs would go unnoticed.") |
| 1543 | + |
| 1544 | + def add_subparsers(self, *args, **kwargs) -> NoReturn: |
| 1545 | + """Raises ``NotImplementedError`` since jsonargparse uses ``add_subcommands``.""" |
| 1546 | + raise NotImplementedError("In jsonargparse subcommands are added using the add_subcommands method.") |
| 1547 | + |
1626 | 1548 |
|
1627 | 1549 | from ._deprecated import parse_as_dict_patch # noqa: E402 |
1628 | 1550 |
|
|
0 commit comments