Skip to content

Commit a1e2c11

Browse files
committed
POC to allow alias
1 parent db0b826 commit a1e2c11

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

jsonargparse/actions.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,11 @@ def _find_action_and_subcommand(
6969
if exclude is not None:
7070
actions = [a for a in actions if not isinstance(a, exclude)]
7171
fallback_action = None
72+
73+
ALLOW_ALIAS = True
74+
7275
for action in actions:
73-
if action.dest == dest:
76+
if action.dest == dest or (ALLOW_ALIAS and dest in get_alias_dest(action)):
7477
if isinstance(action, _ActionConfigLoad):
7578
fallback_action = action
7679
else:
@@ -746,3 +749,11 @@ def handle_subcommands(
746749
# Handle inner subcommands
747750
if subparser._subparsers is not None:
748751
_ActionSubCommands.handle_subcommands(subparser, cfg, env, defaults, key+'.', fail_no_subcommand=fail_no_subcommand)
752+
753+
754+
def get_alias_dest(action):
755+
def option_string_to_var(optstr):
756+
" normalize a cli key as a variable "
757+
return optstr.lstrip('-').replace('-', '_')
758+
759+
return [option_string_to_var(optstr) for optstr in action.option_strings]

jsonargparse/core.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1254,7 +1254,25 @@ def _apply_actions(
12541254
continue
12551255

12561256
action_dest = action.dest if subcommand is None else subcommand+'.'+action.dest
1257-
value = cfg[action_dest]
1257+
ALLOW_ALIAS = 1
1258+
try:
1259+
value = cfg[action_dest]
1260+
except KeyError:
1261+
from jsonargparse.actions import get_alias_dest
1262+
if ALLOW_ALIAS:
1263+
# If the main key isn't in the config, check if it exists
1264+
# under an alias.
1265+
found = None
1266+
for alias in get_alias_dest(action):
1267+
if alias in cfg:
1268+
value = cfg[alias]
1269+
found = True
1270+
break
1271+
if not found:
1272+
raise
1273+
else:
1274+
raise
1275+
...
12581276
if skip_fn and skip_fn(value):
12591277
continue
12601278
with parser_context(parent_parser=self, lenient_check=True):

0 commit comments

Comments
 (0)