On Fri, Jan 9, 2015 at 11:27 PM, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: > Chris Kaynor wrote: > >> Lately, I've been doing quite a bit of work in lua, and many times have >> wished that empty strings, tables, and 0 acted "falsey", but at the same >> time, previously working in Python, there were plenty of times I wished >> they acted "truthy". It merely depends on what algorithm I am using at the >> time... > > > Please do elaborate. I've never found myself in a situation where I have > wanted empty containers to be truthy, and I can't think of what such a > situation would be like.
It's a matter of what you're comparing against. If you might have a thing and might not, the obvious way to arrange things is to have the thing be true and the non-thing be false. That works nicely if that "thing" is an object that's always True, and the "non-thing" is None; for instance, I might have a socket object, and I might not, so I can use "if not self.socket: self.connect()" to ensure that I have one (assuming that self.connect() will throw an error if it fails to establish, blah blah, handwave away the details). This does NOT work if a socket object might be false, so I'd have to explicitly check "if self.socket is None:". Similarly, there are times when the user might have entered a string or might not - say you have an optional parameter "--name" which, if omitted, defaults to some sort of arbitrarily-assigned name; to distinguish between "--name=" and not providing that parameter at all, the logical way is to have name be either a string or None. Again, "if name" would make good sense as meaning "if the --name parameter was provided", rather than "if the --name parameter was provided and not the empty string". If it helps, think of a "nullable field" in databasing. Python's truthiness model is pretty consistent (apart from a few oddities like midnight being false), so I'm not advocating making this change. I'm just explaining the case where the opposite choice does make sense. ChrisA -- https://mail.python.org/mailman/listinfo/python-list