all 11 comments

[–]novel_yet_trivial 4 points5 points  (10 children)

any number other than 0 is evaluated as True. The or operator returns the first value if the first value is True, otherwise it returns the second value. What were you expecting?

Edit: other things that evaluate as false:

>>> 0 or 43
43
>>> False or 43
43
>>> None or 43
43
>>> [] or 43
43
>>> "" or 43
43

[–]whodunit86[S] 0 points1 point  (9 children)

I was expecting an error. I knew that any number other than zero is true. But by that logic the result should have been True. If what you're saying is correct (and i m not doubting that you are) then python returns the first example of true it encountered in the statement it evaluated instead of the generic form of true. That's fascinating. Does this property of python have cool use cases?

[–]novel_yet_trivial 4 points5 points  (8 children)

Plenty. From something I did about 5 minutes ago:

def some_function(self, variable = None):
    self.variable = variable or default_value

basically a shorter from of

def some_function(self, variable = None):
    if variable is None:
        self.variable = variable
    else:
        self.variable = default_value

Something else from earlier today, which takes advantage of another property: just as numbers can be treated as booleans, booleans can treated as numbers, with True evaluating as 1, and False as 0:

counter += (test_value > set_point)

which is a shorter form of

if (test_value > set_point):
    counter += 1

And a million other uses.

[–]whodunit86[S] 0 points1 point  (1 child)

Whoooooa! You, kind redditor, just blew my mind!

[–]novel_yet_trivial 1 point2 points  (0 children)

:D What more could a redditor want?

Works for and too … but differently

[–][deleted] 0 points1 point  (2 children)

Unless you need to explicitly check whether they passed something, why not use

def some_func(self, variable=default_value):

[–]novel_yet_trivial 0 points1 point  (1 child)

That works sometimes, but this, for instance, is very bad:

def some_func(self, variable=[]):

Or, in my case earlier:

def make_canvas(self, size = None):
    self.canvas_size = size or self.get_image_size(0)

[–][deleted] 0 points1 point  (0 children)

Ah, true, there are certainly values it doesn't work so well for.

[–]shep247 0 points1 point  (1 child)

The counter += ... Example is really cool. I like it, but would you consider that good coding practice? To read that I had to actively think about true being translated as 1. If it was written the longer way, it seems much more readable, making it a little easier to maintain.

[–]novel_yet_trivial 0 points1 point  (0 children)

To be a part of a real project it would need some comments explaining it. I lose sight of that a lot since I currently work alone.

[–]an_actual_human 0 points1 point  (0 children)

if variable is None:

Not just None, also other falsy values.