[Python-Dev] Proper way to specify that a method is not defined for a type

Émanuel Barry vgr255 at live.ca
Tue Jun 7 13:55:01 EDT 2016


> From: Ethan Furman
> Sent: Tuesday, June 07, 2016 1:38 PM
> To: Python Dev
> Subject: [Python-Dev] Proper way to specify that a method is not defined
for
> a type

(Just so everyone follows, this is a followup of
http://bugs.python.org/issue27242 )

> For binary methods, such as __add__, either do not implement or return
> NotImplemented if the other operand/class is not supported.
> 
> For non-binary methods, simply do not define.
> 
> Except for subclasses when the super-class defines __hash__ and the
> subclass is not hashable -- then set __hash__ to None.

Should I mention the __hash__ special case in the
NotImplemented/NotImplementedError docs? If people are looking for a way to
declare this specific operation undefined, they'd find it there as well as
the hash() documentation.

> Question:
> 
> Are there any other methods that should be set to None to tell the
> run-time that the method is not supported?  Or is this a general
> mechanism for subclasses to declare any method is unsupported?

There was a discussion on one of Python-ideas or Python-dev some time ago
about exactly that, but I don't think any consensus was reached. However, I
think it would make sense for e.g. __iter__ and __reversed__ to tell the
interpreter to *not* fall back to the default sequence protocol (well, in
practice that already works, but it gives an unhelpful error message). I'm
not sure how useful it would be for arbitrary methods, though. __bytes__
(which originally sparked the issue) may or may not be a good candidate, I'm
not sure.

While I like the `__magic_method__ = None` approach, I think the main reason
__hash__ supports that is because there are legitimate use cases of
disallowing hashing (i.e. mutable objects which may or may not change hash
during their lifetime), but I don't think the same rationale applies to
everything ("accidentally" iterating over a not-meant-to-be-iterable object
will result in nonsensical data, but it won't bite the user later, unlike
changing hashes which definitely will).

> --
> ~Ethan~

Special-cases-aren't-special-enough-but-they're-still-there'ly yrs,
-Emanuel


More information about the Python-Dev mailing list