by frogcoder · 4y ago · 0 comments
Many of my code were like this:
foo = one_or_none()
if foo:
do_stuff(foo)
Now I have the following: if foo := one_or_none():
do_stuff(foo)
This kind of code happens quite frequently, looks nicer with walrus operator to me.In both cases, "foo" continues to exist after the "if" even though the second example makes it look like "foo" is scoped to the "if".
So to my eye, the following would look super weird (assume do_more_stuff can take None):
if foo := one_or_none():
do_stuff(foo)
do_more_stuff(foo)
whereas the following would look fine: foo = one_or_none()
if foo:
do_stuff(foo)
do_more_stuff(foo) for foo in one_or_none():
do_stuff(foo)
If you don't control one_or_none, but it returns an Optional, you can wrap it with something like: def optional_to_tuple(opt_val: Optional[T]) -> Tuple[]|Tuple[T]:
return (opt_val,) if opt_val is not None else () if one_or_none() as foo:
do_stuff(foo)I am not fully up to speed with 3.10, but quickly checked the docs and it doesn't appear to have been added in 3.10 either.
Let me know if I'm missing something.