1

When fetching a number of config values from os.environ, it's nice to have defaults in the python code to easily allow the application to start in a number of contexts. A typical django settings.py has a number of

SOME_SETTING = os.environ.get('SOME_SETTING')

lines.

To provide sensible defaults we opted for

SOME_SETTING = os.environ.get('SOME_SETTING') or "theValue"

However, this is error prone because calling the application with

SOME_SETTING="" 

manage.py

will lead SOME_SETTING to be set to theValue instead of the explicitly defined ""

Is there a way to assign values in python using the ternary a = b if b else d without repeating b or assigning it to a shorthand variable before?

this becomes obvious if we look at

SOME_VERY_LONG_VAR_NAME = os.environ.get('SOME_VERY_LONG_VAR_NAME') if os.environ.get('SOME_VERY_LONG_VAR_NAME') else 'meh'

It would be much nicer to be able to do something like

SOME_VERY_LONG_VAR_NAME = if os.environ.get('SOME_VERY_LONG_VAR_NAME') else 'meh'
martineau
  • 119,623
  • 25
  • 170
  • 301
pascalwhoop
  • 2,984
  • 3
  • 26
  • 40

2 Answers2

5

Just like Python's built-in mapping class dict, os.environ.get has a second argument, and it seems like you want it:

SOME_SETTING = os.environ.get('SOME_SETTING', "theValue")

This is the same as

try:
    SOME_SETTING = os.environ['SOME_SETTING']
except KeyError:
    SOME_SETTING = "theValue"
iBug
  • 35,554
  • 7
  • 89
  • 134
  • Beat me by a couple seconds - but you should edit your post to mention that the `default` argument is not specific to `os.environ.get`, it's for just any dict or dict-like (mapping) types. – bruno desthuilliers Dec 26 '18 at 12:03
  • @brunodesthuilliers Yes, thank you for the heads up. – iBug Dec 26 '18 at 12:04
2

If you read dict.get()'s doc, you'll find out the method's signature is get(self, key, default=None). The default argument is what gets returned if the key is not found in the dict (and default to a sensible None). So you can use this second argument instead of doing an erroneous boolean test:

SOME_SETTING = os.environ.get('SOME_SETTING', "theValue")
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118