in Python, why use "val = param or None' when you can take default params?

Viewed 99

I found some examples like below:

def some_func(param):
    inner_var = param or None
    # rest of codes...

This is used in class as well:

class MyClass:
    def __init__(self, param):
        self.param = param or None

But why use this way, when you can simply use default param syntax? For example,

def some_func(param=None):
    # just use param

like this! also, are there any difference depending on the value after "or"?

2 Answers

Basically they are converting all non-truthy values to None. So the val variable is only ever truthy values or None — never falsy values other than None.

For purposes of having a default value, you should use the latter (third code example) is what you should use — that allows you to avoid needlessly taking in a falsy value only for it to be converted to None.

The other difference is that in the original, callers are required to provide an argument when calling the function. With your proposed change, this would no longer be the case.

Related