Fixing A String Issue with in Mypy

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

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

color = if self._color else \       

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 attribute. I don’t think that applies to my specific error message.

Although 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 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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
C.D. Reimer

C.D. Reimer


C.D. Reimer makes topical videos about comic cons, pop culture, Silicon Valley and technology on YouTube.