HBNetwork / python-decouple

Strict separation of config from code.
MIT License
2.79k stars 192 forks source link

Feature idea: optional value #159

Closed kazet closed 1 year ago

kazet commented 1 year ago

so that e.g. I could write MAX_RETRIES = decouple.config("MAX_RETRIES", cast=Optional(int), default=None), which will be None if MAX_RETRIES is not set and int value if it is.

Currently such configuration produces:

TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
lucasrcezimbra commented 1 year ago

You can create a custom cast function.

MAX_RETRIES = decouple.config("MAX_RETRIES", cast=lambda v: int(v) if v else None, default=None)
henriquebastos commented 1 year ago

You can also achieve this with something like:

class Optional:
    def __init__(self, type):
        self.type = type

    def __call__(self, value):
        try:
            return self.type(value)
        except:
            return None

MAX_RETRIES = decouple.config("MAX_RETRIES", cast=Optional(int), default=None)