Reputation: 391
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)
Upvotes: 1
Views: 996
Reputation: 78546
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
.
Upvotes: 4