1

What's the best way to write a null-check in Python? Try-Except blocks, if blocks...?

Given a function that returns None if the input is None, a valid input, what's the best approach to deal with this situation? Take this function for example:

def urlify(path):
    if path is None:
        return None

    return "<a href=\"{0!s}\">{0!s}</a>".format(path)
3
  • 3
    You could do return path and "<a href=\"{0!s}\">{0!s}</a>".format(path) Commented Dec 12, 2016 at 11:08
  • 1
    I'd avoid using str.format() to generate HTML instead of a proper sanitizing template engine. Too many security holes to leave open. Commented Dec 12, 2016 at 11:15
  • @IgnacioVazquez-Abrams Will do, this was a quick example for a Jinja2 extension filter Commented Dec 12, 2016 at 11:17

1 Answer 1

4

You could use a ternary operator with the return statement to return None if path is None or return something else otherwise.

def urlify(path):
    return path if path is None else "<a href=\"{0!s}\">{0!s}</a>".format(path)

However considering functions return None by default, you can simply do:

def urlify(path):
    if path is not None:
        return "<a href=\"{0!s}\">{0!s}</a>".format(path)

Or as vaultah suggested in the comments, you could also short-circuit using and.

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

3 Comments

I like the first suggestion in cases the return value is brief, otherwise it ends up taking too much horizontal space. The latter is the one I like the most, but is not as obvious that it returns None. I don't really understand short-circuiting using and, I can't comment on his @vaultah suggested.
I personally prefer the short-circuit and, but these choices allow empty strings/False/etc to be passed as well. I suppose it depends on how flexible OP'd like their function to be.
@Alxe (a and b) is (a if not a else b)

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.