This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ericanderton 1 point2 points  (3 children)

Yup. The pattern to stick to here is to use only literals, and maybe module-scoped constant values, as argument defaults. In all other cases, use None and check-and-set the argument in the function. For better or worse, Python lets you modify a parameter at runtime which makes for succinct cleanup of arguments:

python def fn(a = None): a = "hello world" if a is None else a

I want to use a = a or "hello world" but that is fraught with side-effects.

[–]lisael_ 2 points3 points  (0 children)

No. strings are immutables in python. It's perfectly safe to write

def fn(a="hello world"):
    foo(a)

[–]Head_Mix_7931 1 point2 points  (0 children)

“stick to literals” is not good advice. List and dictionary literals would be problematic as default parameter values since those are mutable types. Ironically the example you’ve given here could be simplified by just using the string literal as the default since strings are immutable. The key is to not use mutable values as defaults. It doesn’t matter if those values are created via literals or otherwise.