[Python-Dev] pathlib - current status of discussions (original) (raw)
Nick Coghlan ncoghlan at gmail.com
Sat Apr 16 21:38:11 EDT 2016
- Previous message (by thread): [Python-Dev] pathlib - current status of discussions
- Next message (by thread): [Python-Dev] pathlib - current status of discussions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 17 April 2016 at 04:47, Chris Barker - NOAA Federal <chris.barker at noaa.gov> wrote:
On Apr 13, 2016, at 8:31 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
class Special(bytes): def fspath(self): return 'str-val' obj = Special('bytes-val', 'utf8') pathobj = fspath(obj, allowbytes=True)
With #2, pathobj == 'bytes-val'. With #3, pathobj == 'str-val'. In this kind of case, inheritance tends to trump protocol. Sure, but... 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, OK, but in this case, purity can beat practicality. If the author writes an fspath method, presumably it's because it should be used. And I can certainly imagine one might want to store a path representation as bytes, but NOT want the raw bytes passed off to file handling libs. (of course you could use composition rather than subclassing if you had to)
Exactly - inheritance is a really strong relationship that directly affects the in-memory layout of instances (at least in CPython), and also the kinds of assumption other code will make about that type (for example, subclasses are special cased to allow them to override the behaviour of numeric binary operators when they appear as the right operand with an instance of the parent type as the left operand, while with unrelated types, the left operand always gets the first chance to handle the operation).
When folks don't want to trigger those "this is an " behaviours, the appropriate design pattern is composition, not inheritance (and many of the ABCs were introduced to make it easier to implement particular interfaces without inheriting from the corresponding builtin types).
Cheers, Nick.
-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
- Previous message (by thread): [Python-Dev] pathlib - current status of discussions
- Next message (by thread): [Python-Dev] pathlib - current status of discussions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]