When using the Pylance (ms-python.vscode-pylance) VS Code extension in strict type checking mode, I get a type error on my custom Enum value for the following code:
def println_ctrl_sequence(message: str, ctrlSequence: Union[ANSICtrlSequence, str]):
"""
This function is use with terminals to print the message
with colors specified by a, ANSI control sequence that
can be either a str or a console.ANSICtrlSequence object.
"""
if type(ctrlSequence) == ANSICtrlSequence:
ctrlSequenceStr: str = ctrlSequence.value
else:
ctrlSequenceStr = ctrlSequence
print("%s%s%s" % (
ctrlSequenceStr,
message,
ANSICtrlSequence.RESET.value
))
The type error is detected on the ctrlSequenceStr: str = ctrlSequence.value
line since ctrlSequence.value
is detected as being of type Any | Unknown
. So my objective is to strongly type the value
attribute of my extended Enum
:
# python enum : https://docs.python.org/3/library/enum.html
from enum import Enum
class ANSICtrlSequence(Enum):
# basic control sequences
RESET = "\033[m"
# full control sequences
PASSED = "\033[1;4;38;5;76m"
FAILED = "\033[1;5;38;5;197m"
I have tried things like for instance doing ANSICtrlSequence(str, Enum)
as specified here in "String-based enum in Python" Q&A without success.
I have read the class enum.pyi
and I can understand why the type of value is what it is:
class Enum(metaclass=EnumMeta):
name: str
value: Any
...
I can't find a way to type my value attribute to be a str anywhere in the documentation or on StackOverflow. So is it possible? Is there a way to override the type of an inherited attribute? Or do I need to extend the Enum class with for instance an equivalent of the IntEnum that could be StrEnum for instance? Maybe I need to write my own strongly typed Enum class? Is there anything I missed?