by Mawr · 1y ago · 0 comments
API_KEY = os.environ.get("YOUTUBE_API_KEY")
CHANNEL_ID = os.environ.get("YOUTUBE_CHANNEL_ID")
if not API_KEY or not CHANNEL_ID:
print("Missing YOUTUBE_API_KEY or YOUTUBE_CHANNEL_ID.")
exit(1)
Presenting the user with "Missing X OR Y" when there's no reason that OR has to be there massively frustrates the user for the near zero benefit of having one fewer if statement. if not API_KEY:
print("Missing YOUTUBE_API_KEY.")
exit(1)
if not CHANNEL_ID:
print("Missing YOUTUBE_CHANNEL_ID.")
exit(1)
Way better user experience, 0.00001% slower dev time. 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)?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("...")
...Sometimes that's inevitable, bit noisy of the time it isn't.
exit("Missing ...")
This prints the message and exits with code 1.You can protect passwords in a password manager. You do not need to keep the passwords in env and I do not.
https://typer.tiangolo.com/tutorial/arguments/envvar/
It's especially nice for secrets. Best of both worlds :)
One could write a huge treatise on everything that is wrong with environment variables. Avoid them like the plague. They are a huge usability PITA.
Environment variables are substantially more secure than plain text files because they are not persistent. There are utilities for entering secrets into them without leaking them into your shell history.
That said, you generally should not use an environment variable either. You should use a secure temporary file created by your shell and pass the associated file descriptor. Most shells make such functionality available but the details differ (ie there is no fully portable approach AFAIK).
The other situation that sometimes comes up is that you are okay having the secret on disk in plain text but you don't want it inadvertently commited to a repository. In those cases it makes sense to either do as you suggested and have a dedicated file, or alternatively to set an environment variable from ~/.bashrc or similar.
if not API_KEY and not CHANNEL_ID:
print("Missing both YOUTUBE_API_KEY and YOUTUBE_CHANNEL_ID.")
exit(1)
if not API_KEY:
print("Missing YOUTUBE_API_KEY.")
exit(1)
if not CHANNEL_ID:
print("Missing YOUTUBE_CHANNEL_ID.")
exit(1)
That way you don't end up fixing one just come back and be told you're also missing another requirement valid = True
if not API_KEY:
print("Missing YOUTUBE_API_KEY.")
valid = False
if not CHANNEL_ID:
print("Missing YOUTUBE_CHANNEL_ID.")
valid = False
if not valid:
exit(1)
This way you only check each value once (because your logic might be more complicated than just checking it's not set, maybe it can be wrongly formatted) and you still get to do whatever logic you want. It also removed the combinatorial problems.This is a pretty general principle of separating decision from action.
if not API_KEY:
sys.exit("Missing YOUTUBE_API_KEY.")
It will print message to sys.stderr and do system exit with code 1.P.S. exit() is just an alias to sys.exit(), I prefer longer form.
API_KEY = os.environ.get("YOUTUBE_API_KEY")
CHANNEL_ID = os.environ.get("YOUTUBE_CHANNEL_ID")
assert(API_KEY, "Missing YOUTUBE_API_KEY")
assert(CHANNEL_ID, "Missing CHANNEL_ID")That bit me before... it created a tuple which evaluated as true.
If the user is a typical consumer using a typical consumer interface, then yes you want to handhold them a bit more.
$ python3 -c "print('clear messaging'); exit(1)"
clear messaging
$ python3 -c "raise ValueError('text that matters')"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ValueError: text that matters
and that story gets _a lot_ worse when some programs raise from within a "helper" module and you end up with 8 lines of Python junk to the one line of actual signal