Does Pythonic use bools as ints?

False equivalent to 0 , and True equivalent to 1 , so you can do something like this:

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

Note that the value is bool , but is used as an int .

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

+63
python boolean
Jul 04 2018-10-10T00:
source share
7 answers

I will be a strange voice (since all answers condemn the use of the fact False == 0 and True == 1 , as the language guarantees), since I argue that using this fact to simplify the code is excellent.

Historically, logical operations true / false usually use 0 for false and 1 for true; During the Python 2.2 life cycle, Guido noticed that too many modules started with jobs, such as false = 0; true = 1 false = 0; true = 1 , and this led to the creation of a template and useless variation (the latter due to the fact that the capitalization of true and false was everywhere - some used all-caps, some all-lowercase, some cap-initial) and therefore introduced a subclass of bool int and its constants True and False .

There was quite a bit of response at that time, since many of us were afraid that the new type and constants would be used by Python beginners to limit language possibilities, but Guido was adamant that we were just pessimistic: no one would ever understand Python so badly, for example, to avoid the natural use of False and True as indexes on a list or in summation or other such perfectly clear and useful idioms.

The answers to this question prove that we were right: as we feared, there was a complete misunderstanding of roles of this type and constants, and people avoid and, even worse, convince others to avoid completely natural Python constructs in favor of useless vibrations.

Struggling with the excitement of such a misunderstanding, I urge everyone to use Python as Python, not , trying to drive it into the form of other languages, the functionality and preferred style of which are completely different. In Python, True and False are 99.9%, like 1 and 0, they differ only in the form of str(...) (and thus repr(...) ) - for any operation other than string, just feel free to use them without distortion. This applies to indexing, arithmetic, bit operations, etc. Etc. Etc.

+160
Jul 04 2018-10-04T00:
source share

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

However, in Python 2.5 and later, I will write the answer to this specific question using a Python conditional expression:

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

Thus, there is no requirement that the argument be actually bool - just like if x: ... accepts any type for x , the bool_to_str() function must do the right thing when it is passed to None, a string, a list, or 3.14.

+142
Jul 28 2018-11-21T00:
source share

sure:

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

more readable.

+37
Jul 04 '10 at 10:48
source share

In some cases, your code seems inaccurate:

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

And I recommend using only a conditional operator for readability:

 def bool_to_str(value): """value should be a bool""" return "Yes" if value else "No" 
+12
Jul 05 '10 at 6:10
source share

Actually this is a sign of the language False == 0 and True == 1 (it does not depend on the implementation): Is False == 0 and True == 1 in Python - is the implementation detail or is it guaranteed by the language?

However, I agree with most of the other answers: there are more readable ways to get the same result as ['No', 'Yes'][value] , using … if value else … or a dictionary that have corresponding hint advantages and claiming that value is boolean.

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

+5
Jul 04 '10 at
source share

Using bool as an int is fine, because bool is a subclass of int.

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

About your code: adding it to a single-line function is like the top. Readers need to find the source or documents of the function and read it (the function name does not tell you much). This interrupts the flow. Just put it on a line and don't use a list (built at runtime), 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] 
+1
Jul 05 '10 at 9:16
source share

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

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

     a = 0 if a: do something 
  • However, say that you want to calculate how many elements were successful, the code may not be very readable by other people.

     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 see that the production code is as follows.

 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]) 
0
Dec 23 '16 at 10:43
source share



All Articles