Operator Precedence/Boolean Logic
Chris Angelico
rosuav at gmail.com
Wed Jun 29 07:06:36 EDT 2016
On Wed, Jun 29, 2016 at 8:21 PM, Rustom Mody <rustompmody at gmail.com> wrote:
>
> Please show me how we would define __bool__ for
>
> 1. Graphs -- the kind mathematicians define with "Let G =(V,E) be a graph..."
>
> 2. Automata which in a way are special kinds of graphs
>
> 3. Regular Expressions which mathematically are related to automata
> And pragmatically are (more) present in python than the first two
>
> It may (or may not) be helpful to pretend that python which already has
> a regexp module/type also has explicit regexp syntax a la Perl.
Probably the easiest way, for each of these objects, is to not define
__bool__ at all, or to define it thus:
def __bool__(self):
return True
If an object isn't a container, but is just a "thing", then it is by
definition true. The contrast isn't between [1] and [], but rather
between object() and None. It's perfectly reasonable for an object to
be always true - that's what the default object type does. You could
perhaps argue that a graph can be empty, but unless you're frequently
wanting to distinguish between empty graphs and non-empty graphs, I'd
stick with the default and make them always true. Note, for instance:
>>> bool(re.compile(""))
True
I think that's about as empty as a regex can be, and it's still true.
And regex match objects are always true, too - the match functions
will all return None if there's no match. Not all objects need to be
able to be falsey.
ChrisA
More information about the Python-list
mailing list