update the configuration from a list of strings that is expected to come from the command line, i.e. sys.argv[1:]. The arguments are expected to be in the form of `--arg=value`, and the arg can use . to denote nested sub-attributes. Example: --model.n_layer
(self, args)
| 60 | self.__dict__.update(d) |
| 61 | |
| 62 | def merge_from_args(self, args): |
| 63 | """ |
| 64 | update the configuration from a list of strings that is expected |
| 65 | to come from the command line, i.e. sys.argv[1:]. |
| 66 | |
| 67 | The arguments are expected to be in the form of `--arg=value`, and |
| 68 | the arg can use . to denote nested sub-attributes. Example: |
| 69 | |
| 70 | --model.n_layer=10 --trainer.batch_size=32 |
| 71 | """ |
| 72 | for arg in args: |
| 73 | |
| 74 | keyval = arg.split('=') |
| 75 | assert len(keyval) == 2, "expecting each override arg to be of form --arg=value, got %s" % arg |
| 76 | key, val = keyval # unpack |
| 77 | |
| 78 | # first translate val into a python object |
| 79 | try: |
| 80 | val = literal_eval(val) |
| 81 | """ |
| 82 | need some explanation here. |
| 83 | - if val is simply a string, literal_eval will throw a ValueError |
| 84 | - if val represents a thing (like an 3, 3.14, [1,2,3], False, None, etc.) it will get created |
| 85 | """ |
| 86 | except ValueError: |
| 87 | pass |
| 88 | |
| 89 | # find the appropriate object to insert the attribute into |
| 90 | assert key[:2] == '--' |
| 91 | key = key[2:] # strip the '--' |
| 92 | keys = key.split('.') |
| 93 | obj = self |
| 94 | for k in keys[:-1]: |
| 95 | obj = getattr(obj, k) |
| 96 | leaf_key = keys[-1] |
| 97 | |
| 98 | # ensure that this attribute exists |
| 99 | assert hasattr(obj, leaf_key), f"{key} is not an attribute that exists in the config" |
| 100 | |
| 101 | # overwrite the attribute |
| 102 | print("command line overwriting config attribute %s with %s" % (key, val)) |
| 103 | setattr(obj, leaf_key, val) |
no outgoing calls
no test coverage detected