Reputation: 752
I have a Python script that pulls in some config variables using dotenv_values and sets some initial constants using these. The constants are then passed as arguments to a function. If I define the constants in the global context, I get a type-checking error due to the function expecting a string. If I define the constants within the main function, the type checking is fine (although it doesn't like me using the constant naming style within main).
Here's a simple script that should demonstrate the issue:
"""Type-checking test"""
from dotenv import dotenv_values
config = dotenv_values(".config")
URL = config.get("BASE_URL")
if URL is None:
raise ValueError("BASE_URL is not set in .config file")
def do_a_thing(url: str) -> None:
"""Do a thing"""
print("You passed in a URL:", url)
def main():
"""Main"""
do_a_thing(URL)
if __name__ == "__main__":
main()
This results in the checker flagging the "do_a_thing(URL)" line with:
Argument of type "str | None" cannot be assigned to parameter "url" of type "str" in function "do_a_thing"
Type "str | None" is not assignable to type "str"
"None" is not assignable to "str"
How can I convince the type checker that the do_a_thing function will never be called with a None value?
Upvotes: 0
Views: 68