Operator Precedence/Boolean Logic

Steven D'Aprano steve at pearwood.info
Sun Jul 17 11:58:38 EDT 2016


On Mon, 18 Jul 2016 01:00 am, Rustom Mody wrote:

>> I'm still waiting to hear in what way it is not straightforward. You keep
>> insisting that it isn't, but haven't told us in what way it is not.
> 
> The re/automaton/graph examples were towards this only and I think we are
> running in circles on this.  [Note the persons involved and even the
> specific types involved are in a sense not relevant]

Ah, so its a secret, is it? ;-)


> There is however one point that I briefly alluded that can be expanded on,
> viz. Python’s bool behavior is inconsistent with rest of python’s standard
> behavior.

"Inconsistent" is too strong. Treatment of bools is certainly different from
(say) arithmetic. Python doesn't assume that every object can duck-type as
a number -- there's no standard protocol for coercing HTTPServer objects
into floats, for example.

But bools are not the only "universal" type. Strings are too. All objects
can be coerced to strings, using either str() or repr(). If you define only
one of __str__ or __repr__, Python will use the other. If you define
neither, you will inherit from object. If you are using a classic class in
Python 2, you will inherit the built-in conversion.

Likewise equality: == is expected to work with *every* class, without
exception, so if you fail to define an __eq__ method, Python will use its
own default behaviour (which is to compare object identity).

There are a small, but very important, set of functions which are expected
to work on all objects, and coercion to bool is one of them.


> IOW the details — AttributeError/NameError/TypeError — may differ but in
> general python has a well-established (and IMHO kind) behavior, if
> programmer fails to define something python helpfully says that and makes
> no random guesses.

There is *no random guessing* involved. I've already gone through the steps
of the bool protocol two, three, maybe four times. Why do you misrepresent
this as "random guesses"? There's no element of chance, the protocol is
completely deterministic and documented. There's a preferred API,
__nonzero__ in Python 2 and __bool__ in Python 3, if that isn't defined
there's a fallback using __len__, if that's not defined then the usual
rules of inheritance apply and you inherit from your superclasses.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list