7 ms·
This is nitpicking, but this is a good usecase for the := operator: if not (API_KEY := os.getenv("API_KEY")): ... For internal tools I just let os.env
by gvalkov 1y ago
This is nitpicking, but this is a good usecase for the := operator:
if not (API_KEY := os.getenv("API_KEY")):
...
For internal tools I just let os.environ["API_KEY"] raise a KeyError. It's descriptive enough.
- arthurcolle 1y agoI always forget this syntax exists. When was this introduced?
- gvalkov 1y agoIn Python 3.8 - https://peps.python.org/pep-0572/ https://peps.python.org/pep-0572/
- DangitBobby 1y agoOctober 2019 in Python 3.8 https://docs.python.org/3/whatsnew/3.8.html https://docs.python.org/3/whatsnew/3.8.html
- cranium 1y agoThe Walrus operator! Introduced in Python 3.8 according to the PEP 572. Really nice to combine 1) checking if something exists and 2) act on it
- Iwan-Zotow 1y agoAnd for lambdas
- deleted 1y ago[deleted]
- indymike 1y agoYou forgot to end with "goo goo g'joob" or the less correct Simon and Garfunkel version "coo coo ca choo".
- tyrust 1y agoI write a decent amount of Python, but find the walrus operator unintuitive. It's a little funky that API_KEY is available outside of the `if`, perhaps because I had first seen the walrus operator in golang, which restricts the scope to the block.
- bobbylarrybobby 1y agoThis isn't really unique to the walrus operator, it's just a general python quirk (albeit one I find incredibly annoying). `for i in range(5): ...` will leave `i` bound to 4 after the loop.
- yread 1y agoMaybe Python will get a let one day
- nomel 1y agoOddly enough, "except" variables don't remain bound! try: x = int('cat') except Exception as e: pass print(e) # <- NameError: name 'e' is not defined So, it appears Python actually has three variable scopes (global, local, exception block)?
- agumonkey 1y agoexceptions being the exception is funny somehow
- tough 1y agovery recursive
- fuzztester 1y agoyou can say that again.
- mananaysiempre 1y ago
- deleted 1y ago[deleted]
- lucb1e 1y agoWhy would you use it though? I always thought it a bad thing that legacy code (such as in C or C++) had these side effects inside of checks happening
- make3 1y agono one uses walrus
- pinoy420 1y ago[dead]
- icedchai 1y agoIt seems that way! I briefly experimented with it when it first came out, but never used it in any production code. I've never seen it used by anyone else, either.
- Qem 1y agoI use it very often. Avoids duplication of expensive operations in comprehensions.
- 9cb14c1ec0 1y agoI find it interesting that none of the voluminous python code I've had AI tools generate has ever had a walrus operator in it. Reflects the code they're trained on, I guess.
- ErikBjare 1y agoI use it fairly often
- globular-toast 1y agoWhy are people writing Python like it's Go? Letting the KeyError go is usually fine, but if you want to log it or can recover somehow then: try: API_KEY = os.environ["API_KEY"] except KeyError: logger.exception("...") ...