Fixing A String Issue with Enum.name in Mypy

Not all strings are the same when assigning to a variable.

C.D. Reimer
2 min readMay 20, 2022
Photo by Mel Poole on Unsplash

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 theEnum.name attribute.

My original statement assigned either “White” or “Black” from Enum.name to color based on the bool value of self._color.

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 = Color(self._color).name.capitalize()

The statement worked but mypy reported an error message.

error: Item “None” of “Optional[str]” has no attribute “capitalize”

I saw None and went cross-eyed from my previous encounter in mypy. A quick Google search revealed an open issue for theEnum.name attribute. I don’t think that applies to my specific error message.

Although 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 .capitalize() function.

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.

--

--

C.D. Reimer
C.D. Reimer

Written by C.D. Reimer

C.D. Reimer makes topical videos about comic cons, pop culture, Silicon Valley and technology on YouTube. https://www.youtube.com/cdreimer

No responses yet