On Wed, Apr 13, 2016, at 23:27, Nick Coghlan wrote: > In this kind of case, inheritance tends to trump protocol. For > example, int subclasses can't override operator.index: ... > The reasons for that behaviour are more pragmatic than philosophical: > builtins and their subclasses are extensively special-cased for speed > reasons, and those shortcuts are encountered before the interpreter > even considers using the general protocol. > > In cases where the magic method return types are polymorphic (so > subclasses may want to override them) we'll use more restrictive exact > type checks for the shortcuts, but that argument doesn't apply for > typechecked protocols where the result is required to be an instance > of a particular builtin type (but subclasses are considered > acceptable).
Then why aren't we doing it for str? Because "try: path = path.__fspath__()" is more idiomatic than the alternative? If some sort of reasoned decision has been made to require the protocol to trump the special case for str subclasses, it's unreasonable not to apply the same decision to bytes subclasses. The decision should be "always use the protocol first" or "always use the type match first". In other words, why not this: def fspath(path, *, allow_bytes=False): if isinstance(path, (bytes, str) if allow_bytes else str) return path try: m = path.__fspath__ except AttributeError: raise TypeError path = m() if isinstance(path, (bytes, str) if allow_bytes else str) return path raise TypeError _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com