-
Notifications
You must be signed in to change notification settings - Fork 288
How to decrease the type checking paranoia? #1629
-
I've been trying to have my code as clear as possible in terms of typing suggestions but I always end up ignoring a few of them to prevent the code quality violation, the one that most annoys me is this example below.
I'm writing one API service then usually what I do is:
- create a config.py file with some content like this:
from os import getenv as env
CONNECTION_STRING = env("CONNECTION_STRING")
... and some more entries like this
then I assert them
env_vars = [CONNECTION_STRING]
for vars in env_vars:
assert vars is not None
From this part, I'm already making sure that this variable cannot be None, but when I import this constant in another file that I may have or not use it as an argument I always end up with something like...
Argument of type "str | None| cannot be assigned to parameter...
So my point is I don't want to check if these constants are None on every piece of code that I need to use, so maybe I'm not sure if I'm doing it properly or indeed we need some extra, extra, extra value validation before using it...
Beta Was this translation helpful? Give feedback.
All reactions
Maybe create a helper function like this:
def env_not_none(key: str) -> str: value = os.getenv(key) assert value is not None, f"failed to find {key}" return value CONNECTION_STRING = env_not_none("CONNECTION_STRING")
Replies: 1 comment 2 replies
-
Maybe create a helper function like this:
def env_not_none(key: str) -> str: value = os.getenv(key) assert value is not None, f"failed to find {key}" return value CONNECTION_STRING = env_not_none("CONNECTION_STRING")
Beta Was this translation helpful? Give feedback.
All reactions
-
that sounds great, just tried and worked perfectly, also it answered some extra answers that I had in mind. Thanks!
Beta Was this translation helpful? Give feedback.
All reactions
-
You could also use os.environ["CONNECTION_STRING"]. That will fail if the env var doesn't exist.
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 5