Hacker News new | ask | show | jobs
by robot_no_421 1033 days ago
I'm a Python dev who uses this feature frequently. But the more I use Python (and the more I use Rust in my spare time), the more I realize that I use it only because it's what Python expects me to do. If it was up to me I'd much rather use

  if my_container.empty():
      # do stuff
than

  if not my_container:
      # do stuff
The second implementation behaves the same if either my_container is None or if my_container is empty (or if my_container is 0 or ""...), whereas the first implementation allows me to handle those cases differently. The first implementation is also more explicit and easier to understand on a first read.

It's also easier to debug. Is users supposed to be None in your example? Possibly, but your code doesn't give me any hints. Is my_container supposed to be None in my example? Probably not based on the way I explicitly used the .empty() method.

1 comments

Python’s type annotations carry the same information, but explicitly. If fetch_users() returns a list of users, you know exactly what “users” is and whether it can be None.

Really, though, list.empty() is canonically spelled “not list” in Python. That’s the idiom to learn, read, and write.