Confix cannot be used without a valid config file
rmca opened this issue · comments
I have an application where I want to use a default config specified using confix. I want to override this config only when a config file exists, otherwise I want the specified defaults to be used. If you call parse without a path to a valid config file it will error out. Furthermore, if the result of parsing the config file is anything other than a dictionary, then default values with schemas are not initialised, so I don't see a way to achieve this with the current API.
I think this could be handled with a minor refactor like so: rmca@b4debf0
That way at least the caller can handle the case of a non-existent config in a sensible way, while still being able to continue the initialisation of confix and use it for specifying a default config. Alternatively, the parse() function could be reworked to handle this case, but that seems like it would probably require an API change if backwards compatibility is to be maintained. Thoughts?
Can't you simply avoid to call parse()?
Not if one of the config options uses a schema? Take for example the following code:
from __future__ import print_function
from confix import register, parse, schema
@register('ftp')
class config:
port = schema(default=21, validator=lambda x: isinstance(x, int))
user = 'ftp'
password = None # this will be overridden later
if __name__ == '__main__':
parse('config.yaml') # make replacements to "config" class
print(config.user) # will print "ftp"
print(config.port)
Assume you have config.yaml with the contents '{}' (so this will deserialise to empty dict and leave the defaults intact). Running the code above prints "ftp" followed by "21". Now if we comment out the call to parse() the program prints "ftp" followed by "field(default=21, required=False, ...)", the representation of the schema instance. Calling type(config.port) shows us that it is of type: confix.schema. So, avoiding the call to parse() means that the schema never gets initialised to its default value, which means I cannot treat port above as an int. Or am I missing something?
Yes, you are right, I didn't take schemas into account. Can you please submit a pull request?
Sorry for the delay. I'll try and get something done on this over the next week or so.