4 ms·
Linters can help a ton with stuff like this, I think pylint warns against this footgun. Also is there a reason for not using the shorter: var = var or [] Ins
by DanielVZ 5y ago
Linters can help a ton with stuff like this, I think pylint warns against this footgun.
Also is there a reason for not using the shorter:
var = var or []
Instead of:
var = [] if var is None else var
- Asraelite 5y agoI think using `or` for default fallbacks is generally considered bad practice because it disallows all falsey values, like `0` and `{}`. It doesn't matter in this particular case because the only falsey List is `[]` anyway, but it's a bad habit. JavaScript added the `??` operator for this specific problem.
- dragonwriter 5y agoBoth mypy and pyright/pylance do the right thing when things are guarded with explicit None checks and the wrong thing with “or”, so even though I prefer “or” otherwise when its gated upstrean so that None is the only falsey value it should get, I’ve taken recently to using explicit checks to make typecheckers happy.
- Mehdi2277 5y agoThat's not been my experience. I frequently use or way and have both mypy/pyright enabled. Testing this toy function, from typing import List, Optional def f(x: Optional[List[int]]): x = x or [] reveal_type(x) mypy and pyright both show List[int] as type of x at the end and correctly drop None.
- patrick451 5y agoI've never thought of this as a footgun. It's useful to accumulate state in a function, sort of like a static variable in c. E.g., def func(x=[]): x.append(5) return x I've always been annoyed that pylint yells at you for this.
- ViViDboarder 5y agoThe issue is that it’s a non-apparent side effect to an outside caller.