Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The 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 [2]: https://docs.python.org/2/glossary.html#term-lbyl



Is 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.


To 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: