Fixing A String Issue with Enum.name in Mypy
While cleaning up code in a chess program that I’m writing in Python as a learning exercise, I came across yet another problem with the mypy static type checker. This time with the
My original statement assigned either “White” or “Black” from
color based on the
bool value of
color = Color.WHITE.name.capitalize() if self._color else \ Color.BLACK.name.capitalize()
The statement worked and mypy had no problem with it, but it could be shorter. I replaced the inline
if-else statement by passing the
bool value directly to
Color to return corresponding
name string for capitalization and assignment to
color = Color(self._color).name.capitalize()
The statement worked but mypy reported an error message.
error: Item “None” of “Optional[str]” has no attribute “capitalize”
Enum.name outputs a
str that the
.capitalize() function modified appropriately, I didn’t bother to find a way to type hint the statement and make it mypy compliant.
A quick workaround was to wrap
Enum.name with the
str() function, which does have the
color = str(Color(self._color).name).capitalize()
The statement worked, mypy was happy, and shorter than the original version. While redundant to have the
str() function convert a
str output to a
str, the statement has a clearer meaning than before.
Please follow me on Medium. Your support is greatly appreciated.