type annotations for Config allow mismatched default type #1731
Answered
by
Kludex
chdsbd
asked this question in
Potential Issue
-
With the current type stubs, it's possible to specify a default of a different type from the Additionally, this type annotation isn't supported by mypy: BOOL_DEFAULT_STR = config("BOOL_DEFAULT_STR", cast=bool, default="true")
reveal_type(BOOL_DEFAULT_STR) # Revealed type is "builtins.list[builtins.object]"mypy(note) I suggest we make the types more strict to disallow this error case, at the cost of disallowing the valid use case of an from starlette.config import Config
config = Config()
# valid. Default converts to 1
INT_WITH_BOOL_DEFAULT = config("INT_WITH_BOOL_DEFAULT", cast=int, default=True)
INT_WITH_STR_DEFAULT = config("INT_WITH_BOOL_DEFAULT", cast=int, default="True")
# >>> INT_WITH_STR_DEFAULT = config("INT_WITH_BOOL_DEFAULT", cast=int, default="True")
# Traceback (most recent call last):
# File "/Users/christopherdignam/projects/starlette/starlette/config.py", line 146, in _perform_cast
# return cast(value)
# ValueError: invalid literal for int() with base 10: 'True'
# During handling of the above exception, another exception occurred:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/Users/christopherdignam/projects/starlette/starlette/config.py", line 102, in __call__
# return self.get(key, cast, default)
# File "/Users/christopherdignam/projects/starlette/starlette/config.py", line 117, in get
# return self._perform_cast(key, default, cast)
# File "/Users/christopherdignam/projects/starlette/starlette/config.py", line 148, in _perform_cast
# raise ValueError(
# ValueError: Config 'INT_WITH_BOOL_DEFAULT' has value 'True'. Not a valid int. Would a PR be accepted that made the type stricter to disallow both of these examples? |
Beta Was this translation helpful? Give feedback.
Answered by
Kludex
Jan 14, 2024
Replies: 1 comment 1 reply
-
Yes. PR is welcome. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
Kludex
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes. PR is welcome.