Skip to content

Commit df6b37f

Browse files
Only parse one top key if the key name matches the target object
1 parent b529c42 commit df6b37f

1 file changed

Lines changed: 14 additions & 11 deletions

File tree

accelforge/util/_basetypes.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -471,10 +471,16 @@ def from_yaml(
471471
rval = rval[top_key]
472472

473473
c = None
474+
exc = None
474475
try:
475476
c = cls(**rval, **kwargs)
476477
except Exception as e:
477-
pass
478+
exc = e
479+
480+
rval_dict = isinstance(rval, dict)
481+
rval_one_key = rval_dict and len(rval.keys()) == 1
482+
key = next(iter(rval.keys())) if rval_one_key else None
483+
key_matches_my_name = key == cls.__name__.lower()
478484

479485
if c is None and rval is None:
480486
if top_key is not None:
@@ -486,24 +492,21 @@ def from_yaml(
486492
f"No data to parse from {files}. Is there content in the file(s)?"
487493
)
488494

489-
if c is None and len(rval) == 1:
490-
logging.warning(
491-
f"Trying to parse a single element dictionary as a {cls.__name__}. "
492-
)
495+
elif c is None and key_matches_my_name:
496+
logging.warning(f"Parsing contents under {key} into {cls.__name__}. ")
493497
try:
494-
rval_first = list(rval.values())[0]
495-
if not isinstance(rval_first, dict):
498+
if not isinstance(rval[key], dict):
496499
raise TypeError(
497500
f"Expected a dictionary as the top-level element in {files}, "
498-
f"got {type(rval_first)}."
501+
f"got {type(rval[key])}."
499502
)
500-
c = cls(**rval_first, **kwargs)
503+
c = cls(**rval[key], **kwargs)
501504
except Exception as e:
502505
logging.warning(
503506
f"Error parsing {files} with top key {top_key}. " f"Error: {e}"
504507
)
505-
if c is None:
506-
c = cls(**rval, **kwargs)
508+
elif c is None:
509+
raise exc
507510

508511
if extra_elems:
509512
logging.info(

0 commit comments

Comments
 (0)