Skip to content

Add support for config directories #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions argbind/argbind.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,18 @@ def dump_args(args, output_path):
output.append(line)
f.write('\n'.join(output))

def load_args(input_path_or_stream):
def load_args(input_path_or_stream, config_directory = "."):
"""
Loads arguments from a given input path or file stream, if
the file is already open.

If config_directory is specified, the input path and all transitive
imports will be loaded relative to that directory. Streams and
absolute filepaths will not be affected.
"""
if isinstance(input_path_or_stream, (str, Path)):
with open(input_path_or_stream, 'r') as f:
input_path = Path(config_directory) / input_path_or_stream
with open(input_path, 'r') as f:
data = yaml.load(f, Loader=yaml.Loader)
else:
data = yaml.load(input_path_or_stream, Loader=yaml.Loader)
Expand All @@ -244,7 +249,7 @@ def load_args(input_path_or_stream):
include_files = data.pop('$include')
include_args = {}
for include_file in include_files:
include_args.update(load_args(include_file))
include_args.update(load_args(include_file, config_directory))
include_args.update(data)
data = include_args

Expand Down
23 changes: 23 additions & 0 deletions tests/test_argbind.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
import argbind
import contextlib
import os


@contextlib.contextmanager
def temporary_working_directory(path):
original_working_directory = os.getcwd()
os.chdir(path)

try:
yield
finally:
os.chdir(original_working_directory)


def test_load_args():
arg1 = argbind.load_args("examples/yaml/conf/base.yml")
with open("examples/yaml/conf/base.yml") as f:
arg2 = argbind.load_args(f)
assert arg1 == arg2


def test_config_directory():
with temporary_working_directory("tests"):
arg1 = argbind.load_args("examples/yaml/conf/exp2.yml", config_directory="..")
with open("examples/yaml/conf/exp2.yml") as f:
arg2 = argbind.load_args(f)

assert arg1 == arg2