you necessarily provide the reader with fewer hints as to what is actually in that variable
Then make it explicit. I much prefer this:
defdo_foo(bar: list | None):
ifnot bar:
return
...
This one communicates to me that the function only makes sense with a non-empty list.
To this:
defdo_foo(bar):
iflen(bar) == 0:
return
This just tells me bar is something that has a length (list, dict, str, etc).
And this is way worse:
defdo_foo(bar: list | None):
iflen(bar) == 0:
return
This tells me we want an exception if bar is None, which I think is bad style, given that we’re explicitly allowing None here. If we remove the | None and get an exception, than the code is broken because I shouldn’t be able to get that value in that context.
If I care about the difference between None and empty, then I’ll make that explicit:
if bar isNone:
...
ifnot bar:
...
In any case, I just do not like iflen(bar)== 0 because that looks like a mistake (i.e. did the dev know it could throw an error if it’s not a list? Was that intentional?).
Then make it explicit. I much prefer this:
def do_foo(bar: list | None): if not bar: return ...
This one communicates to me that the function only makes sense with a non-empty list.
To this:
def do_foo(bar): if len(bar) == 0: return
This just tells me
bar
is something that has a length (list, dict, str, etc).And this is way worse:
def do_foo(bar: list | None): if len(bar) == 0: return
This tells me we want an exception if
bar
isNone
, which I think is bad style, given that we’re explicitly allowingNone
here. If we remove the| None
and get an exception, than the code is broken because I shouldn’t be able to get that value in that context.If I care about the difference between
None
and empty, then I’ll make that explicit:if bar is None: ... if not bar: ...
In any case, I just do not like
if len(bar) == 0
because that looks like a mistake (i.e. did the dev know it could throw an error if it’s not a list? Was that intentional?).