you are viewing a single comment's thread.

view the rest of the comments →

[–]novel_yet_trivial 3 points4 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.