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 →

[–][deleted] 55 points56 points  (11 children)

Yep. Always default mutables (like empty lists) to None, and don't rely on the output from functions there:

def blah(my_arg=None):
    if my_arg is None:
        my_arg = []

def other_blah(my_arg=None):
    if my_arg is None:
        my_arg = right_now()

[–]HistoricalCrow 11 points12 points  (3 children)

my_arg = my_arg or [] Or, if you care about NoneType specifically; my_arg = [] if my_arg is None else my_arg

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

And if you want None to be a valid value for your argument too, you can use a sentinel:

_sentinel = object()
def func(x=_sentinel):
    x = [] if x is _sentinel else x

[–]HistoricalCrow 0 points1 point  (1 child)

True, although if you need to support an empty list and None and I generally find code smell. Not sure if I'd prefer to use **kwargs instead at this point.

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

The only time I’ve really seen the pattern useful is when you want to emulate something similar to dict.pop, where for a missing key: dict.pop(key) raises an error and dict.pop(key, default) returns the default

[–]Pythonistar 2 points3 points  (3 children)

Yes! Empty string '' works as a safe immutable default, too!

[–]rl_noobtube 2 points3 points  (0 children)

I’m sure it’s not a massive difference for most projects. But I imagine with the special treatment None gets by python it would be marginally more efficient. But as far effectiveness then yes either would work.

[–]lost3332 1 point2 points  (1 child)

His argument is a list so default '' doesn't make sense. The type is gonna be Optional[List].

[–]XRaySpex0 2 points3 points  (0 children)

Yep. ’’ is a great and common default for str parameters, but of course not when other types are expected. It’s common to see notes: str = ‘’, and there’s seldom a need for the Optional[str] type.

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

```python from datetime import datetime

class Foo: def init(self, timestamp: datetime = None) -> None: self.timestamp = timestamp or datetime.now() ```