if not x then … end
is very common in Lua for similar purposes, very rarely do you see hard nil comparisons or calls to typeof
(last time I did was for a serializer).
Comment on Python Performance: Why 'if not list' is 2x Faster Than Using len()
thebestaquaman@lemmy.world 3 weeks agoI would say it depends heavily on the language. In Python, it’s very common that different objects have some kind of Boolean interpretation, so assuming that an object is a bool because it is used in a Boolean context is a bit silly.
Glitchvid@lemmy.world 3 weeks ago
iAvicenna@lemmy.world 3 weeks ago
Well fair enough but I still like the fact that len makes the aim and the object more transparent on a quick look through the code which is what I am trying to get at. The supporting argument on bools wasn’t’t very to the point I agree.
That being said is there an application of “not” on other classes which cannot be replaced by some other more transparent operator (I confess I only know the bool and length context)? I would rather have transparently named operators rather than having to remember what “not” does on ten different types. I like duck typing as much as the next guy, but when it is so opaque as in the case of not, I prefer alternatives. For instance having open or read on different objects which does really read or open some data vs not some object god knows what it does I should memorise each case.
jerkface@lemmy.ca 3 weeks ago
Truthiness is so fundamental, all values have a truthiness, whether they are bool or not. Even in C,
int x = value(); if (!x) x_is_not_zero();
is valid and idiomatic.iAvicenna@lemmy.world 3 weeks ago
I don’t know, it throws me off but perhaps because I always use len in this context. Is there any generally applicable practical reason why one would prefer “not” over len? Is it just compactness and being pythonic?
jerkface@lemmy.ca 3 weeks ago
thebestaquaman@lemmy.world 2 weeks ago
I definitely agree that
len
is the preferred choice for checking the emptiness of an object, for the reasons you mention. I’m just pointing out that assuming a variable is a bool because it’s used in a Boolean context is a bit silly, especially in Python or other languages where any object can have a truthiness value, and where this is commonly utilised.iAvicenna@lemmy.world 2 weeks ago
It is not “assume” as in a conscious “this is probably a bool I will assume so” but more like a slip of attention by someone who is more used to the bool context of not. Is “not integer” or “not list” really that commonly used that it is even comparable to its usage in bool context?
thebestaquaman@lemmy.world 2 weeks ago
Then I absolutely understand you :)
How common it is 100 % depends on the code base and what practices are preferred. In Python code bases where I have a word in decisions, all Boolean checks should be
x is True
orx is False
ifx
should be a Boolean. In that sense, if I readif x
orif not x
, it’s an indicator thatx
doesn’t need to be a Boolean.