[Tutor] What is the difference between checking false?
Dave Angel
davea at davea.name
Sun Jun 16 06:41:20 CEST 2013
On 06/15/2013 11:53 PM, Jim Mooney wrote:
> On 15 June 2013 20:48, Joel Goldstick <joel.goldstick at gmail.com> wrote:
>
>> One and zero for True and False may seem not quite right today,
>
> I still think they should be taken out and shot ;')
>
> But my simplification plan failed. Equality always fails for different
> types, and 'not in front of None or any empty object such as empty
> string, empty list, empty tuple, or empty dict, is always True. But it
> appears that idea fails for an empty class:
>
> class NobodyHome: pass
> x = NobodyHome()
> print(not x) # Result is False when I thought this would be True.
>
The rules you're talking are not somehow mystically enforced by the
compiler. They're definitions and conventions that are presumably
consistently applied in the library code for each builtin or library
type. But if you write your own, you get to make your own rules for if
it's truthey or falsey.
Saying the class is empty is meaningless. Even a trivial class has many
methods that it inherits from object. Anyway, if a class does not
define its own truthy/falsey definition, then an instance of that class
is always considered truthey.
The convention about list, tuple, dict, etc. is referring to
collections, that implement a __len__() method. Add such a method to
your class, and you too can decide whether a particular instance is
truthey or falsey.
But since your class isn't a collection, it'd be clearer to define the
method __bool__(), which is what's tried first. (In Python 3.x)
>>> class NobodyHome:
... def __bool__(self):
... return False #normally, you'd be testing some attribute to
decide this
...
>>> x = NobodyHome()
>>> not x
True
--
DaveA
More information about the Tutor
mailing list