Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to decrease the type checking paranoia? #1629

Discussion options

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...

You must be logged in to vote

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

Comment options

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")
You must be logged in to vote
2 replies
Comment options

that sounds great, just tried and worked perfectly, also it answered some extra answers that I had in mind. Thanks!

Comment options

You could also use os.environ["CONNECTION_STRING"]. That will fail if the env var doesn't exist.

Answer selected by pelissarisergioo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /