Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26655

Should these expressions evaluate differently?

I was somewhat confused until I found the bug in my code. I had to change

a.matched_images.count #True when variable is 0

to

a.matched_images.count > 0 #False when variable is 0

Since I quickly wanted to know whether an object had any images, the first code will appear like the photo has images since the expression evaluates to True when the meaning really is false ("no images" / 0 images)

Did I understand this correctly and can you please answer or comment if these expressions should evaluate to different values.

Upvotes: 1

Views: 94

Answers (3)

Ethan Furman
Ethan Furman

Reputation: 69051

What is the nature of count? If it's a basic Python number, then if count is the same as if count != 0. On the other hand, if count is a custom class then it needs to implement either __nonzero__ or __len__ for Python 2.x, or __bool__ or __len__ for Python 3.x. If those methods are not defined, then every instance of that class is considered True.

Upvotes: 3

Daniel May
Daniel May

Reputation: 8226

Without knowing what count is, it's hard to answer, but this excerpt may be of use to you:.

The following values are considered false:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]

All other values are considered true — so objects of many types are always true.

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96266

>>> bool(0)
False

So.. no, if it were an int that wouldn't matter. Please do some tracing, print out what count actually is.

Upvotes: 1

Related Questions