Created
July 7, 2017 20:49
-
-
Save pirogoeth/6031b2ba0c453f22a01897b16149e08c to your computer and use it in GitHub Desktop.
Python method to "tap" a config object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dict_tap(path, default=None): | |
""" Retrieves the path through a dictionary. | |
"The config is a lot like an onion - it has layers" | |
example: | |
>>> dict_tap( | |
>>> 'otp.age_threshold', | |
>>> default=2, | |
>>> ) | |
""" | |
parts = path.split('.') | |
layer = _CONFIG | |
for part in parts: | |
if part.isdigit(): | |
# Use part as an array index | |
part = int(part) | |
try: | |
layer = layer[part] | |
except IndexError: | |
return default | |
else: | |
if not layer: | |
return default | |
layer = layer.get(part, default) | |
if layer == default: | |
return default | |
return layer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment