Replies: 1 comment
-
An alternative I can think of, is to use a bunch of overloads: class GeneralConf:
@overload
def __getitem__(self, key: Literal[
"language",
"loggingLevel",
]) -> str: ...
@overload
def __getitem__(self, key: Literal[
"saveConfigurationOnExit",
"askToExit",
"playStartAndExitSounds",
"showWelcomeDialogAtStartup",
"preventDisplayTurningOff"
]) -> bool: ...
# actual implementation
def __getitem__(self, key: str) -> Any:
... which seemed to be working in VS Code. It can list all possible literals after typing the left bracket, just like a |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I tried to enable Pyright rules, and I saw many type checking errors related to
config.conf
.Type-hinting
config.conf
is challenging.configobj.Section.__getitem__
can return many different types of values, such as a string, an integer, or a sub section. This makes static type checking difficult. For example,config.conf["general"]["loggingLevel"]
, how can a static type checker determine thatconfig.conf["general"]
is a section, andconfig.conf["general"]["loggingLevel"]
is a string?Worse, configobj currently lacks support for static type checking. Someone is working on this, though.
If you type-hint
__getitem__
with every possible type, such asSection | str | int | ...
, the type checker will still not able to determine the actual type, and will warn on operations not possible for some of the types. If you type hint withAny
though, the type checker will allow anything, but then you lose the type checking ability, unless you explicitly mark the type at the caller's end, such aslevel: str = config.conf["general"]["loggingLevel"]
.Type-checking for dictionaries can be achieved with
TypedDict
, which allows different keys to be mapped to different types of values.It can work well with pure dictionaries, but
config.conf
is not just a dictionary, which can cause problems becauseTypedDict
is treated as adict
at runtime.So
Conf
,GeneralConf
andConfigManager
are not separate types at runtime. Also, defining extra member functions in a TypedDict is not allowed.What are your ideas about how to type hint
config
?Beta Was this translation helpful? Give feedback.
All reactions