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

If I know my_dict doesn't hold values that that are false-like, e.g. 0 or [], I use `or` to lazily alternate between options. This works because in python, `or` returns the first value that has a truthy value. In this case it would be

    my_dict.get('existing_key') or foo()
This would also easily let you do multiple alternations (much more annoying with the ternary operator).


This is dangerous because sometimes you have legitimate values that are not truthy.

  print(player_data['score'] or 'does not exist')
This will print "does not exist" when the score is zero.


gp's approach works best when you know that the argument is a list or tuple (something which can be empty). Of course, due to python's lack of typing, you should only use that approach when the function is being used in well-understood contexts.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

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

Search: