71

False is equivalent to 0 and True is equivalent 1 so it's possible to do something like this:

def bool_to_str(value):
    """value should be a bool"""
    return ['No', 'Yes'][value]

bool_to_str(True)

Notice how value is bool but is used as an int.

Is this this kind of use Pythonic or should it be avoided?

hwiechers
  • 14,583
  • 8
  • 53
  • 62
  • 1
    This is essentially a duplicate of http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail-or-is-it-guarantee, whose answers make for an interesting read too! – Eric O. Lebigot Feb 17 '11 at 10:32

7 Answers7

176

I'll be the odd voice out (since all answers are decrying the use of the fact that False == 0 and True == 1, as the language guarantees) as I claim that the use of this fact to simplify your code is perfectly fine.

Historically, logical true/false operations tended to simply use 0 for false and 1 for true; in the course of Python 2.2's life-cycle, Guido noticed that too many modules started with assignments such as false = 0; true = 1 and this produced boilerplate and useless variation (the latter because the capitalization of true and false was all over the place -- some used all-caps, some all-lowercase, some cap-initial) and so introduced the bool subclass of int and its True and False constants.

There was quite some pushback at the time since many of us feared that the new type and constants would be used by Python newbies to restrict the language's abilities, but Guido was adamant that we were just being pessimistic: nobody would ever understand Python so badly, for example, as to avoid the perfectly natural use of False and True as list indices, or in a summation, or other such perfectly clear and useful idioms.

The answers to this thread prove we were right: as we feared, a total misunderstanding of the roles of this type and constants has emerged, and people are avoiding, and, worse!, urging others to avoid, perfectly natural Python constructs in favor of useless gyrations.

Fighting against the tide of such misunderstanding, I urge everybody to use Python as Python, not trying to force it into the mold of other languages whose functionality and preferred style are quite different. In Python, True and False are 99.9% like 1 and 0, differing exclusively in their str(...) (and thereby repr(...)) form -- for every other operation except stringification, just feel free to use them without contortions. That goes for indexing, arithmetic, bit operations, etc, etc, etc.

bignose
  • 30,281
  • 14
  • 77
  • 110
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 9
    +1 Contrast with Ruby, which forces `val?1:0` and similar gymnastic junk if you need to treat a bool as an int. – John La Rooy Jul 05 '10 at 00:32
  • 31
    "nobody would ever understand Python so badly, for example, as to avoid the perfectly natural use of False and True as list indices". I'm certainly not opposed to using them that way, but I in no way think it's "natural" for people to index into a list with a boolean type, unless they happen to know that `bool` subclasses `int` – Michael Mrozek Jul 06 '10 at 14:50
  • 4
    Interesting history lesson indeed! However, I would argue that there is something telling in the fact that most people distinguish between booleans and integers (I do…). In a way, people are defining what it means to "use Python as Python": most of us do feel that there is a logical distinction between the two types (mathematics mostly do too: logic does not need arithmetic). I'm quite happy with the fact that Python allows us to think this way. – Eric O. Lebigot Jul 07 '10 at 10:26
  • As dahlia's answer shows, the index approach is unnecessarily restrictive (compared to the `… if … else …` approach). – Eric O. Lebigot Jul 07 '10 at 10:31
  • 2
    I cannot believe I disagree with Alex, but I do. Using booleans as indexes in this situation avoids duck typing, whereas ``'True' if value else 'False'`` works with any truish ``value``. – mcepl Jul 25 '16 at 10:18
158

I'm with Alex. False==0 and True==1, and there's nothing wrong with that.

Still, in Python 2.5 and later I'd write the answer to this particular question using Python's conditional expression:

def bool_to_str(value):
  return 'Yes' if value else 'No'

That way there's no requirement that the argument is actually a bool -- just as if x: ... accepts any type for x, the bool_to_str() function should do the right thing when it is passed None, a string, a list, or 3.14.

Guido van Rossum
  • 16,690
  • 3
  • 46
  • 49
41

surely:

def bool_to_str(value):
    "value should be a bool"
    return 'Yes' if value else 'No'

is more readable.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 2
    I would argue with that one... yes, using the `x if foo else y` thingy is more pythonic, but I still think that it just looks ugly and often bloats code. I think the code in the question **looks** clearer, it may be confusing for people who don't know about the implicit bool to int conversion, but `x if foo else y` is just as confusing for someone that comes from the `foo ? x : y` world of things. Even though I have to admit, that for people which are learning their first language, the `x if foo else y` may be the clearest one. – Ivo Wetzel Jul 04 '10 at 10:54
  • 2
    @Ivo, +1 as I agree on the substance, but I disagree that the "ternary" construct (with the condition in the middle, not at the start like in C) is particularly natural or clear to newbies (it's the least of evils in many cases -- that's a different thing;-). – Alex Martelli Jul 04 '10 at 16:13
  • not sure, looks like I got one, too, at about the same time (and also w/o comments!). – Alex Martelli Jul 04 '10 at 20:01
  • 1
    Come on, @AlexMartelli, Python's "ternary" construct is _so_ natural it can be straightforwardly read as plain English and be understood even by non-programmers. "_return yes if this is true, else no_". This a blessing of elegance and natural language for newbies. – MestreLion Nov 06 '18 at 18:49
13

Your code seems inaccurate in some cases:

>>> def bool_to_str(value):
...     """value should be a bool"""
...     return ['No', 'Yes'][value]
...
>>> bool_to_str(-2)
'No'

And I recommend you to use just the conditional operator for readability:

def bool_to_str(value):
    """value should be a bool"""
    return "Yes" if value else "No"
minhee
  • 5,688
  • 5
  • 43
  • 81
  • 19
    The function's name is `bool_to_str`, with doc comment `value should be a bool`, and you're surprised that it gives a wrong answer when you pass it `-2` :) – Michael Mrozek Jul 06 '10 at 14:54
  • On the other hand, I would argue that it is usual to assume that non-0 means True… What dahlia's example shows is that the `… if … else …` method allows you to produce code that is not unnecessarily restrictive. – Eric O. Lebigot Jul 07 '10 at 10:29
  • 4
    +1 While I agree with Alex Martelli's answer in general, in this case it seems "more Pythonic" to take advantage of the implicit conversion to `bool` afforded by `... if ... else ...`. Then the function works for bools and anything else. Though perhaps just not the best example, as I don't disagree with the idea of using bools as ints. – anton.burger Jul 07 '10 at 11:01
  • If you don't know whether the value you are receiving is a strict boolean (i.e. `True` or `False`) or a "truthy expression" (e.g. `a and b or c`) then simply apply the `bool` function to the value. Simples! – holdenweb Nov 16 '16 at 08:40
5

It is actually a feature of the language that False == 0 and True == 1 (it does not depend on the implementation): Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?

However, I do agree with most of the other answers: there are more readable ways of obtaining the same result as ['No', 'Yes'][value], through the use of the … if value else … or of a dictionary, which have the respective advantages of hinting and stating that value is a boolean.

Plus, the … if value else … follows the usual convention that non-0 is True: it also works even when value == -2 (value is True), as hinted by dahlia. The list and dict approaches are not as robust, in this case, so I would not recommend them.

Community
  • 1
  • 1
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
1

Using a bool as an int is quite OK because bool is s subclass of int.

>>> isinstance(True, int)
True
>>> isinstance(False, int)
True

About your code: Putting it in a one-line function like that is over the top. Readers need to find your function source or docs and read it (the name of the function doesn't tell you much). This interrupts the flow. Just put it inline and don't use a list (built at run time), use a tuple (built at compile time if the values are constants). Example:

print foo, bar, num_things, ("OK", "Too many!)[num_things > max_things]
John Machin
  • 81,303
  • 11
  • 141
  • 189
0

Personally I think it depends on how do you want to use this fact, here are two examples

  1. Just simply use boolean as conditional statement is fine. People do this all the time.

    a = 0
    if a:
        do something
    
  2. However say you want to count how many items has succeed, the code maybe not very friendly for other people to read.

    def succeed(val):
        if do_something(val):
            return True
        else:
            return False
    
    count = 0
    values = [some values to process]
    for val in values:
        count += succeed(val)
    

But I do see the production code look like this.

all_successful = all([succeed(val) for val in values])
at_least_one_successful = any([succeed(val) for val in values])
total_number_of_successful = sum([succeed(val) for val in values])