4 ms·
It's a dynamic-typing thing. In some hypothetical static-strong-non-duck version of Python, if name != '' and len(pets) > 0 and owners != {} would tell you
by bcoates 13y ago
It's a dynamic-typing thing. In some hypothetical static-strong-non-duck version of Python,
if name != '' and len(pets) > 0 and owners != {}
would tell you that name is a non-empty string, pets has values, and owners is a non-empty dict (except it doesn't work, as pdonis noticed).
But Python allows immoral implicit conversions, so that's not what that line means! If name is a function, pets is the value '7' and owners is a list, the test passes.
if name and pets and owners
Would pass as well, but it has the advantage of not implying it does more than it does: all you can infer from the test passing is that none of name,pets,owners are special falsy values.
If you actually wanted to test what the longer line is implying, you'd write something like
if isinstance(name, str) and isinstance(pets, list) and isinstance(owners, set) and name and pets and owners
(don't do this, it violates duck-typing and LBYL)
- pdonis 13y agoowners is a non-empty set. No, it doesn't tell you that. {} denotes an empty dict, not an empty set; and an empty set will return True for owners != {}, not False. As I noted in another post upthread, you would need to write len(owners) > 0 to get the correct semantics, making owners indistinguishable from pets even if they are different container types. If you really wanted to make all the types clear, you would need to include the isinstance tests.
- bcoates 13y agoYou're right, edited.
- bo1024 13y agoSure, if you view the code as a conversation between the reader and the compiler, but as a conversation between the reader and the writer, I would hope that those inferences (e.g. name is a non-empty string) would be reasonable.