Skip to content

Conversation

@luandy64
Copy link
Contributor

This commit adds an example of how someone could write a function to update a config file, as mentioned in this PR.


def update_config_file(config_path, new_config):
with open(config_path, 'w') as output:
output.write(json.dumps(new_config, indent=2))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit concerned about the API here, due to the possibility of accidentally zeroing out the config.

I wonder if it would make more sense to take a key and a value, then add or update that in the file, instead of replacing the file itself? That way there is no way to delete things from the config, just add them as it needs.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. I like the idea of mirroring the metadata API here.

def delete(compiled_metadata, breadcrumb, k):
del compiled_metadata[breadcrumb][k]
def write(compiled_metadata, breadcrumb, k, val):
if val is None:
raise Exception()
if breadcrumb in compiled_metadata:
compiled_metadata.get(breadcrumb).update({k: val})
else:
compiled_metadata[breadcrumb] = {k: val}
return compiled_metadata
def get(compiled_metadata, breadcrumb, k):
return compiled_metadata.get(breadcrumb, {}).get(k)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we're talking about API design, one possible extension to the metadata approach, would be to have a 3-arity write that assumes that breadcrumb = tuple(). Could be nicer for simple uses of the API, at the cost of a bit more complexity in the code (type checking the second arg, etc).

I'm not familiar with the Pythonic way to do multi-arity, maybe just defining the function twice is enough, or it might have to be *args with explicit run-time checking code.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think pythonic here would be a default value for breadcrumb breadcrumb=[].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants