4 ms·
It really depends. Usually, you would do something like this in Python: def whatever(some_string): try: return some_string.split() except Attri
by odonnellryan 11y ago
It really depends. Usually, you would do something like this in Python:
def whatever(some_string):
try:
return some_string.split()
except AttributeError:
return some_other_parsing_stuff(some_string)
Instead of checking the type of some_string, or seeing if it has the method split. Reason is: it's more straight forward, and it instantly tells the reader this function is meant to handle strings, and it will split them. If it gets a not-string for some reason, oh well, it'll still handle it.
You would check for values in a circumstance like this:
def dict_breaker(some_dict):
if 'items' in some_dict:
return parse_some_items(some_dict['items'])
- dbaupp 11y agoThe latter isn't actually the typical Python style. As the article discusses, Python generally prefers "EAFP"[1] to "LBYL"[2], e.g. def dict_breaker(some_dict): try: return parse_some_items(some_dict['items']) except KeyError: pass Or even def dict_breaker(some_dict): try: items = some_dict['items'] except KeyError: pass else: return parse_some_items(items) These versions may be more efficient (only have to do one hash and interaction with the hashmap, but this probably won't be visible with integers/short strings), and don't suffer from race conditions in concurrent code with the hashmap being modified between the check and the use (yes, this can occur even with GIL). [1]: https://docs.python.org/2/glossary.html#term-eafp https://docs.python.org/2/glossary.html#term-eafp [2]: https://docs.python.org/2/glossary.html#term-lbyl https://docs.python.org/2/glossary.html#term-lbyl
- kornish 11y agoIs there a reason you chose to `pass` instead of the more explicit `return None`? The former seems like it would be less idiomatic since its return value is not explicitly stated.
- dbaupp 11y agoTo emulate the parent exactly e.g. maybe it is just the prefix of the "dict_breaker" function and other things happen later if the key can't be found.