Q:

Return object - python inline if

I'm tring to write the one line equivalent to:
if userSet in Cluster.salientGroupCache:
            return Cluster.salientGroupCache[userSet]

So, i tried:
return Cluster.salientGroupCache[userSet] if userSet in Cluster.salientGroupCache else None

But this line returns Cluster.salientGroupCache[userSet] or None depnding on the evaluation of the expression.
The following gives me an error:
None if not userSet in Cluster.salientGroupCache else return Cluster.salientGroupCache[userSet]

Is there a way to selective return a value using inline if, and if not I would appreciate an explanation as to why.

A:

You can write your first code on one line if you want:
if userSet in Cluster.salientGroupCache: return Cluster.salientGroupCache[userSet]

This is not great style, but it does exactly what you want. You can't use an if expression for this because return is a statement, and you can't nest a statement inside an expression.

A:

You want a 1 line-code? Why? 
If it's about style and performance then start by doing only one lookup in Cluster.salientGroupCache:
try:
    return Cluster.salientGroupCache[userSet]
except KeyError:  # or another error (it's a dict, right?)
    pass

That's probably faster and more pythonic because it follows the EAFP principle: "Easier to ask for forgiveness than permission."

About your exception:
None if not userSet in Cluster.salientGroupCache else return Cluster.salientGroupCache[userSet]
#              that's not allowed in an expression----^^^^^^

However the:
return Cluster.salientGroupCache[userSet] if userSet in Cluster.salientGroupCache else None

should work without problems.

