Skip to content

Commit

Permalink
Fix loading of an empty file via a file-pointer to return an empty di…
Browse files Browse the repository at this point in the history
…ctionary (omry#404)
  • Loading branch information
omry authored Oct 5, 2020
1 parent ea210fb commit 3e5853d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 10 deletions.
1 change: 1 addition & 0 deletions news/403.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix loading of an empty file via a file-pointer to return an empty dictionary
22 changes: 12 additions & 10 deletions omegaconf/omegaconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,21 +283,23 @@ def load(file_: Union[str, pathlib.Path, IO[Any]]) -> Union[DictConfig, ListConf
if isinstance(file_, (str, pathlib.Path)):
with io.open(os.path.abspath(file_), "r", encoding="utf-8") as f:
obj = yaml.load(f, Loader=get_yaml_loader())
if obj is None:
res = OmegaConf.create()
else:
res = OmegaConf.create(obj)
assert isinstance(res, (ListConfig, DictConfig))
return res
elif getattr(file_, "read", None):
obj = yaml.load(file_, Loader=get_yaml_loader())
assert isinstance(
obj, (list, dict, str)
), f"Invalid loaded object type : {type(obj).__name__}"
return OmegaConf.create(obj)
else:
raise TypeError("Unexpected file type")

if obj is not None and not isinstance(obj, (list, dict, str)):
raise IOError( # pragma: no cover
f"Invalid loaded object type : {type(obj).__name__}"
)

ret: Union[DictConfig, ListConfig]
if obj is None:
ret = OmegaConf.create()
else:
ret = OmegaConf.create(obj)
return ret

@staticmethod
def save(
config: Any, f: Union[str, pathlib.Path, IO[Any]], resolve: bool = False
Expand Down
3 changes: 3 additions & 0 deletions tests/test_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,3 +182,6 @@ def test_load_empty_file(tmpdir: str) -> None:
empty.touch()

assert OmegaConf.load(empty) == {}

with open(empty) as f:
assert OmegaConf.load(f) == {}

0 comments on commit 3e5853d

Please sign in to comment.