config2py.base#
Base for getting configs from various sources and formats
Module Attributes
the default |
|
the lookup errors, plus |
|
any exception from a callable source means "not found". |
Functions
|
Ask the user for the value of |
|
Get a config value from a list of sources |
|
Convert an iterable of sources into |
|
True unless |
True unless |
|
|
Create a |
|
Create a |
Classes
|
A class that wraps a |
|
|
- config2py.base.DFLT_CONFIG_NOT_FOUND_EXCEPTIONS: tuple[type[Exception], ...] = (<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>)#
the default
config_not_found_exceptions. Any other error raised by a callable source (a network blip, a bug, a missing import, rejected credentials) propagates instead of silently falling through to the next, possibly less trusted, source (issue #25).- Type:
The exceptions that mean “this source has no value for the key”
- config2py.base.DFLT_USER_PROMPT_NOT_FOUND_EXCEPTIONS: tuple[type[Exception], ...] = (<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>, <class 'EOFError'>)#
the lookup errors, plus
EOFError, whichinput()raises when there is no one to ask (stdin closed or at end of file: cron, CI, a subprocess). So a prompt that cannot be answered falls through toget_config’sdefaultinstead of crashing.- Type:
What the user-prompt source (
user_gettable) treats as “not found”
- class config2py.base.FuncBasedGettableContainer(getter, val_is_valid=<function always_true>, config_not_found_exceptions=(<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>))[source]#
Bases:
objectA class that wraps a
Callable[[KT], VT]function so it has a (partial) Mapping[KT, TT] interface. It is “partial” in the sense that it only implements__getitem__, raise aKeyErrorwhen a key can’t be computed. This is the standard forMappingtypes, which enables us to use theFuncBasedGettablein acollections.ChainMapto catch the error and move on to the next source.>>> def getter(k): ... if k == 'foo': ... return 'quux' ... elif k == 'green': ... return 'eggs' ... else: ... raise LookupError(f"I don't handle that: {k}") >>> gc = FuncBasedGettableContainer(getter) >>> gc['foo'] 'quux' >>> gc['green'] 'eggs'
Observe below that though the
getterfunction raises aLookupError, theFuncBasedGettableContainerraises aKeyError, to conform to theMappingprotocol.>>> gc['no_a_key'] Traceback (most recent call last): ... KeyError: 'no_a_key'
The
KeyErrormessage is just the key: neither the upstream exception text nor the rejected value is interpolated into it, since getters commonly wrap credential checks and these errors commonly end up in logs. The upstream exception is still available, through the standard exception chain:>>> try: ... gc['no_a_key'] ... except KeyError as e: ... print(type(e.__cause__).__name__, e.__cause__, sep=': ') LookupError: I don't handle that: no_a_key
Note that by default,
FuncBasedGettableContaineronly turns the “not found” exceptions ofDFLT_CONFIG_NOT_FOUND_EXCEPTIONSinto aKeyError; any other error the getter raises propagates. Passconfig_not_found_exceptionsto choose a different set (LEGACY_CONFIG_NOT_FOUND_EXCEPTIONS, i.e.(Exception,), catches everything).Note as well that you can specify a
val_is_validfunction that will be used to check the value returned by thegetterfunction. If the value is not valid, aKeyErrorwill also be raised. This is useful, for example, when you have a function that returns a sentinel likeNoneinstead of raising an exception, but you want to treat that as aKeyError.>>> def getter(k): ... if k == 'foo': ... return 'quux' ... elif k == 'green': ... return 'eggs' ... else: ... return None >>> gc = FuncBasedGettableContainer(getter, val_is_valid=lambda x: x is not None) >>> gc['foo'] 'quux' >>> gc['no_a_key'] Traceback (most recent call last): ... KeyError: 'no_a_key'
- class config2py.base.GettableContainer(*args, **kwargs)[source]#
Bases:
ProtocolContainersthat are “gettable””.By “gettable”, we mean that we can fetch an element from
objwith brackets:obj[k]. That is,objhas a__getitem__method. AContainermeans thatobjhas a__contains__method, i.e. the expressionk in objis valid.>>> isinstance(3, GettableContainer) # 3 is not Gettable (can't do 3[...]) False
But
dict,list, andstrare GettableContainer:>>> isinstance([1, 2, 3], GettableContainer) True >>> isinstance({'foo': 'bar'}, GettableContainer) True >>> isinstance('foo', GettableContainer) True
Note that so are their types:
>>> all(isinstance(c, GettableContainer) for c in (list, dict, str)) True
But
setis not aGettableContainer.>>> myset = {1, 2, 3} >>> isinstance(myset, GettableContainer) False
This is because a
setis aContainer, but it is not gettable:>>> 4 in myset # set is a container False >>> myset[4] # ... but not gettable Traceback (most recent call last): ... TypeError: 'set' object is not subscriptable
- config2py.base.LEGACY_CONFIG_NOT_FOUND_EXCEPTIONS: tuple[type[Exception], ...] = (<class 'Exception'>,)#
any exception from a callable source means “not found”. Pass it as
config_not_found_exceptionsto keep falling through on every error.- Type:
The default before config2py 0.1.80
- config2py.base.ask_user_for_key(key=None, *, prompt_template='Enter a value for {}: ', save_to=None, save_condition=<function is_not_empty>, user_asker=<function ask_user_for_input>, egress=None)[source]#
Ask the user for the value of
key, optionally saving it.- Parameters:
key – The key to ask the user for. If
None, a “curried” version ofask_user_for_keyis returned, so you can specify the key later.prompt_template (
str) – A template string to prompt the user with. It should contain a placeholder for the key, e.g."Enter a value for {}: ".save_to (
Union[MutableMapping,Callable[[KT,VT],Any],None]) – Where to save the user’s response: aMutableMapping(or anything with a__setitem__), or a(key, value)saver function. IfNone, the response is not saved. See_resolve_saver.save_condition (
Callable[[object],bool]) – A function of the value, deciding whether to save it.user_asker (
Callable[[str],str]) – A function that takes a prompt string and returns the user’s response.egress (
Callable|None) – A(key, value)function to apply to the user’s response before returning (and saving) it.
The value can be saved to any
MutableMapping:>>> store = {} >>> ask_user_for_key('some_key', save_to=store, user_asker=lambda prompt: 'val') 'val' >>> store {'some_key': 'val'}
… or to a
(key, value)function, when saving isn’t a simple write:>>> saved = [] >>> ask_user_for_key( ... 'some_key', ... save_to=lambda k, v: saved.append((k, v)), ... user_asker=lambda prompt: 'val', ... ) 'val' >>> saved [('some_key', 'val')]
- config2py.base.get_config(key=None, sources=None, *, default=Sentinel('no_default'), egress=None, val_is_valid=<function always_true>, config_not_found_exceptions=(<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>))[source]#
Get a config value from a list of sources
A source can be a function or a
GettableContainer. (AGettableContaineris anything that can be indexed with brackets:obj[k], likedict,list,str, etc..).Let’s take two sources: a
dictand aCallable.>>> def func(k): ... if k == 'foo': ... return 'quux' ... elif k == 'green': ... return 'eggs' ... else: ... raise KeyError(k) >>> dict_ = {'foo': 'bar', 'baz': 'qux'} >>> sources = [func, dict_]
See that
get_configgo through the sources in the order they were listed, and returns the first value it finds (or manages to compute) for the key:get_configfinds'foo'in the very first source (func):>>> get_config('foo', sources) 'quux'
But
bazmakesfuncraise an error, so it goes to the next source:dict_. There, it finds'baz'and returns its value:>>> get_config('baz', sources) 'qux'
On the other hand, no one manages to find a config value for
'no_a_key', soget_configraises an error:>>> get_config('no_a_key', sources) Traceback (most recent call last): ... config2py.errors.ConfigNotFound: Could not find config for key: no_a_key
But if you provide a default value, it will return that instead:
>>> get_config('no_a_key', sources, default='default') 'default'
You can also provide a function that will be called on the value before it is returned. This is useful if you want to do some post-processing on the value, or if you want to make sure that the value is of a certain type:
This “search the next source if the previous one fails” behavior only applies to errors that mean “not found”: the
config_not_found_exceptionsargument, which defaults toDFLT_CONFIG_NOT_FOUND_EXCEPTIONS(KeyError,LookupError,FileNotFoundError,ConfigNotFound). Any other error raised by a callable source (a network blip, a bug, a missing import, rejected credentials) propagates, rather than being hidden by a silent move to the next, possibly less trusted, source:>>> def flaky(k): ... raise RuntimeError("network blip") >>> get_config('foo', [flaky, dict_]) Traceback (most recent call last): ... RuntimeError: network blip
Pass
config_not_found_exceptions=LEGACY_CONFIG_NOT_FOUND_EXCEPTIONS(that is,(Exception,), the default before config2py 0.1.80) to fall through on any error (see i2mint/config2py#25):>>> get_config('foo', [flaky, dict_], ... config_not_found_exceptions=LEGACY_CONFIG_NOT_FOUND_EXCEPTIONS) 'bar'
Further, your sources may return a value, but not one that you consider valid: For example, a sentinel like
None. In this case you may want the search to continue. This is what theval_is_validargument is for. It is a function that takes a value and returns a boolean. If it returnsFalse, the search will continue. If it returnsTrue, the search will stop and the value will be returned.Finally, we have
egress : Callable[[KT, TT], VT]. This is a function that takes a key and a value, and returns a value. It is called after the value has been found, and its return value is the one that is returned byget_config. This is useful if you want to do some post-processing on the value, or before you return the value, or if you want to do some caching.>>> config_store = dict() >>> def store_before_returning(k, v): ... config_store[k] = v ... return v >>> get_config('foo', sources, egress=store_before_returning) 'quux' >>> config_store {'foo': 'quux'}
Note that a source can be a callable or a
GettableContainer(most of the time, aMapping(e.g.dict)). Here, you should be compelled to use the resources ofdol(https://pypi.org/project/dol/) which will allow you to makeMappingobjects for all sorts of data sources.For more info, see: i2mint/config2py#4
- config2py.base.gettable_containers(sources, val_is_valid=<function always_true>, config_not_found_exceptions=(<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>))[source]#
Convert an iterable of sources into
GettableContainers- Return type:
- config2py.base.is_not_empty(val)[source]#
True unless
valisNoneor the empty string.>>> is_not_empty(None) False >>> is_not_empty('') False >>> is_not_empty('a') True >>> is_not_empty(0) True
- Return type:
- config2py.base.is_not_none_nor_empty(x)[source]#
True unless
xisNoneor the empty string.>>> is_not_none_nor_empty(None) False >>> is_not_none_nor_empty('') False >>> is_not_none_nor_empty('a') True >>> is_not_none_nor_empty(0) True
- Return type:
- config2py.base.sources_chainmap(sources, val_is_valid=<function always_true>, config_not_found_exceptions=(<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>))[source]#
Create a
ChainMapfrom a list of sources- Return type:
- config2py.base.user_gettable(save_to=None, *, prompt_template='Enter a value for {}: ', egress=None, user_asker=<function ask_user_for_input>, val_is_valid=<function is_not_empty>, config_not_found_exceptions=(<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>, <class 'EOFError'>))[source]#
Create a
GettableContainerthat asks the user for a value, optionally saving it.- Parameters:
save_to (
Union[MutableMapping,Callable[[KT,VT],Any],None]) – Where to save the user’s response: aMutableMapping(or anything with a__setitem__), or a(key, value)saver function. IfNone, the user’s response is not saved.prompt_template (
str) – A template string to prompt the user with. It should contain a placeholder for the key, e.g."Enter a value for {}: ".egress (
Callable|None) – A function to apply to the user’s response before returning it. This can be used to validate the response, for example.user_asker (
Callable[[str],str]) – A function that asks the user for input. It should take a prompt string and return the user’s response.val_is_valid (
Callable[[VT],bool]) – A function that takes a value and returns a boolean. If it returnsFalse, the user will be asked for a new value.config_not_found_exceptions (
tuple[type[Exception],...]) – The exceptions that mean “the user gave no value”: the key is then treated as not found, andget_configmoves on (or returns itsdefault). Defaults toDFLT_USER_PROMPT_NOT_FOUND_EXCEPTIONS: the lookup errors plusEOFError. Any other error (fromegressvalidation, say) propagates, with its own text.
When nobody can answer the prompt, the key is “not found” too: an
EOFErrororOSErrorraised byuser_asker(stdin at end of file, unreadable, or captured by pytest), or aRuntimeErrorwhilesys.stdinisNone(stdin closed), is re-raised asUserInputUnavailable, aConfigNotFound.- Returns:
A
GettableContainerthat asks the user for a value, optionally saving it.
Example
>>> s = user_gettable() >>> v = s['SOME_KEY'] 'SOME_VAL'
This will trigger a prompt for the user to enter the value of
SOME_KEY. When they do (say they entered ‘SOME_VAL’) it will return that value.And if you specify a save_to store (usually a persistent MutableMapping made with the
dolpackage) then it will save the value to that store for future use.>>> d = dict(some='store') >>> s = user_gettable(save_to=d) >>> s['SOME_KEY'] 'SOME_VAL' >>> d {'some': 'store', 'SOME_KEY': 'SOME_VAL'}
When saving isn’t a simple write (say you need to encrypt, or write to two places),
save_tocan be a(key, value)function instead:>>> saved = [] >>> s = user_gettable( ... save_to=lambda k, v: saved.append((k, v)), ... user_asker=lambda prompt: 'SOME_VAL', ... ) >>> s['SOME_KEY'] 'SOME_VAL' >>> saved [('SOME_KEY', 'SOME_VAL')]