HBNetwork / python-decouple

Strict separation of config from code.
MIT License
2.83k stars 196 forks source link

Add a new built in helper Choices #86

Closed danielgoncalves closed 4 years ago

danielgoncalves commented 4 years ago

This helper allows for cast and validation of configuration values based on a list of choices and/or Django-like choices tuple. For example:

>>> from decouple import config, Choices
>>> os.environ['SOME_NUMBER'] = '42'
>>> config('SOME_NUMBER', cast=Choices([7, 14, 42], cast=int))
42

or, based on a Django-like choices tuple:

>>> USB = 'usb'
>>> ETH = 'eth'
>>> BLUETOOTH = 'bluetooth'
>>>
>>> CONNECTION_OPTIONS = (
...        (USB, 'USB'),
...        (ETH, 'Ethernet'),
...        (BLUETOOTH, 'Bluetooth'),)
...
>>> os.environ['CONNECTION_TYPE'] = BLUETOOTH
>>> config('CONNECTION_TYPE', cast=Choices(choices=CONNECTION_OPTIONS))
'bluetooth'

Raises ValueError if configuration value is not listed:

>>> os.environ['CONNECTION_TYPE'] = 'serial'
>>> config('CONNECTION_TYPE', cast=Choices(choices=CONNECTION_OPTIONS))
Traceback (most recent call last):
  ...
ValueError: Value not in list: 'serial'; valid values are ['eth', 'usb', 'bluetooth']
henriquebastos commented 4 years ago

Show!