2 ms·
I disagree. An empty string is False. Any empty set is False. An empty dict is False. Basically, in Python emptiness implies falseness. This has practical benef
by kstrauser 3y ago
I disagree. An empty string is False. Any empty set is False. An empty dict is False. Basically, in Python emptiness implies falseness. This has practical benefits:
users = database.fetch_users()
if not users:
print("Didn't find anyone.")
and
name = input()
if not name:
print("You didn't enter a name.")
Of course you could work around those like `if len(users) == 0` or `if not len(users)` or `if name != ""`, but each of those is uglier.
`if not users` translates very nicely to English: "if there are not any users...". I'm glad Python defined `bool(list)` that way.
- robot_no_421 3y agoI'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.
- kstrauser 3y agoPython’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.