简体   繁体   中英

How to avoid repetition in a ternary operator assignment?

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'

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"

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM