2

I'm trying to do a conditional assignment based on the return value for environmental variables.

self._TBLFilePath = iTBLFilePath or os.environ.get("CDO_TBLPATH") + os.environ.get("CDO_INSTANCE_TYPE") + ".tbl" or os.environ.ge    t("CDO_ROOT") + "/cdo/tbl/" + os.environ.get("CDO_INSTANCE_TYPE") + ".tbl"

The problem is when CDO_TBLPATH is undefined I get a string with None concatenation error. I wonder if there is a way to force None + string to return a None as well, or is there any other way to overcome this?

Thanks.

2 Answers 2

3

mapping.get() supports a 'default' argument:

os.environ.get("CDO_TBLPATH", '')

The default is to return None, but by specifying an empty string your concatenation will work even if CDO_TBLPATH is not defined.

You cannot have the concatenation magically return None if the .get() return None; you could use a custom class that returns None in a __add__ method but I'm not sure if that'd be very readable.

If you need to skip any of the options (not concatenate) if the environment variable is not defined, you'd be better off splitting out the tests:

table_options = (
    (lambda: iTBLFilePath, lambda: iTBLFilePath)
    (lambda: os.environ.get("CDO_TBLPATH") and os.environ.get("CDO_INSTANCE_TYPE"),
        lambda: os.environ["CDO_TBLPATH"] + os.environ["CDO_INSTANCE_TYPE"] + '.tbl'),
    (lambda: os.environ.get("CDO_ROOT") and os.environ.get("CDO_INSTANCE_TYPE"),
        lambda: os.environ["CDO_ROOT"] + "/cdo/tbl/" + os.environ["CDO_INSTANCE_TYPE"] + ".tbl"),
    (lambda: True, lambda: None),
)

self. _TBLFilePath = next(opt() for tst, opt in table_options if tst())

This defines a series of tests, and the value associated with the first test that is successful is used.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, if my question was a bit confusing. What I actually want to achieve is that the second operand (os.environ.get("CDO_TBLPATH") + os.environ.get("CDO_INSTANCE_TYPE") + ".tbl") would return False/None in case one of those env variables is not set
0

For this, I sometimes borrow the coalesce() function from SQL. In Python, it works this way:

coalesce = lambda *a: next((i for i in a if i is not None), None)

or maybe better

def coalesce(*a):
    """Return the first non-`None` argument, or `None` if there is none."""
    return next((i for i in a if i is not None), None)

It returns the first non-None argument, or None if there is none.

If there was no default argument for .get(), you could do

coalesce(get('...'), '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.