by Buttons840 · 4y ago · 0 comments
# Instead of doing this
if len(numbers) == 0:
print("The numbers list is empty")
# Many of us do this
if not numbers:
print("The numbers list is empty")
I tend to write the first form because it is how I think, and I'm writing what I think. "If this list is empty, then..." I suppose a list is only falsy if it is empty. I used to exploit Python's truthyness / falsyness a lot more, but now I like to be more explicit. Ultimately it doesn't matter much, making a single line a tiny bit longer is rarely the most important issue in a project. def custom_sum(numbers: Optional[List[int]] = None) -> int:
if not numbers:
## something
return sum(numbers)
This can handle both cases - if numbers is None, or numbers is [] bool(0) -> False
bool(1) -> True
bool(str('0')) -> True
bool(str('')) -> False
bool(None) -> False
If you are checking that a variable is set bool(some_var) doesn't work for 0. if numbers == []:
print ("The numbers list is empty")
if your intent is to express "is the list empty?" in the condition?It will fail for non-list inputs, which is another reason it can be handy if you want clarify that you’re enforcing a list.
It will fail for non-list inputs, which is another reason it can be handy if you want clarify that you’re enforcing a list.
len will work for strings, tuples, dicts, sets, plus all kinds of custom classes that implement the __len__ magic method.
I just want to enforce that the object acts like a list, mainly versus a float, int, or boolean. Tuples are definitely 100% ok, and if someone wants to give me a set, that's almost certainly OK too, in the use cases I'm considering. And so is a numpy vector!
Often these objects are held in a container (a dict or class variable), so type annotations would be clumsy as far as I know. Wouldn't I need to create a separate object to enforce the annotation?
And the type annotation would need to allow tuples and all flavors of lists or numpy arrays.
On the other end of the scale, I don't think either of us wants to use isinstance checks!
My primary intent isn't to be bulletproof, it's to show intent. The main fail of using len() in this way is that it accepts strings.
Type checking via mypy, pyright, etc., is great, but in library (as opposed to an app) you can't count on consumers doing that, and isinstance() checks don't support duck-typing.