[issue39081] pathlib '/' operator does not resolve Enums with str mixin as expected

Karthikeyan Singaravelan report at bugs.python.org
Wed Dec 18 02:40:18 EST 2019


Karthikeyan Singaravelan <tir.karthi at gmail.com> added the comment:

As per the fspath PEP https://www.python.org/dev/peps/pep-0519/#c-api the below precedence is set. So for the enum inheriting from str the object itself is returned and MyEnum.RED.__str__ is used returning MyEnum.RED. You can remove inheritance from str and implement __fspath__ for your enum class to be used as per fspath protocol.

> If the object is str or bytes, then allow it to pass through with
  an incremented refcount. If the object defines __fspath__(), then
  return the result of that method. All other types raise a TypeError.

# bpo39081.py

import os
import pathlib
import enum

class MyEnum(enum.Enum):
    RED = 'red'

    def __fspath__(self):
        return self.name

print(os.fspath(MyEnum.RED))
print(pathlib.Path.home() / MyEnum.RED)

$ python3.8 bpo39081.py
RED
/Users/kasingar/RED

----------
nosy: +ethan.furman, xtreak

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39081>
_______________________________________


More information about the Python-bugs-list mailing list