by gvalkov · 1y ago · 0 comments
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. 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)? e = 'before'
try:
x = int('cat')
except Exception as e:
e2 = e
print(e)
print(e2) # <- This works!
print(e) # <- NameError: name 'e' is not defined
It's not a scoping thing, the bound exception variable is actually deleted after the exception block, even if it was already bound before!https://stackoverflow.com/questions/24271752
https://docs.python.org/3/reference/compound_stmts.html#exce...
It's not that odd, since it's the only situation where you cannot keep it bounded, unless you enjoy having variables that may or may not be defined (Heisenberg variable?), depending on whether the exception has been raised or not?
Compare with the if statement, where the variable in the expression being tested will necessarily be defined.
edit: writing from phone on couch and the laptop... looks far, far away...
This "feature" was responsible for one of the worst security issues I've seen in my career. I love Python, but the scope leakage is a mess. (And yes, I know it's common in other languages, but that shouldn't excuse it.)
But if something fails in a loop running in the repl or jupyter I already have access to the variables.
If I want to do something with a loop of data that is roughly the same shape, I already have access to one of the the items at the end.
Short circuiting/breaking out of a loop early doesn't require an extra assignment.
I really can't see the downside.
Python really is a bit of a mess haha.
>>> s = "abc"
>>> [x:=y for y in s]
['a', 'b', 'c']
>>> x
'c'
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
Comprehensions have their own local scope for their local variables, but the walrus operator reaches up to the innermost "assignable" scope.The last time I wrote Python in a job interview, one of the interviewers said "wait, I don't know Python very well but isn't this kinda an old style?" Yes, guilty. My Python dates me.
Really nice to combine 1) checking if something exists and 2) act on it
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("...")
...