Fixing A String Issue with Enum.name 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 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 makes topical videos about comic cons, pop culture, Silicon Valley and technology on YouTube. https://www.youtube.com/cdreimer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Web Template Engines and Agile UI

Apps That Make MacOS a Better Operating System to Use

The Art of Coding — Use of Spies

Kollect’s Testnet Launch Winner Announcement

[Jogos em Directo]!!!@!!!Assistir Porto x Juve ao vivo online Tv

8 CSS selectors DO’s and DON’Ts (part 2)

HTB — Previse Walkthroughs

[CTF Series #10] Reversing Shadow Clone With Ghidra

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. https://www.youtube.com/cdreimer

More from Medium

Fixing Incompatible Dunder Method Error in Mypy

Dissecting VSCode Python extension by a dumb approach

[Solved] Pytest Error: ImportError: Error importing plugin ‘’: No module named …

Decorators