sizmailov / pybind11-stubgen

Generate stubs for python modules
Other
232 stars 47 forks source link

Add special type hinting for __hash__ to declare class as unhashable #110

Closed TheTripleV closed 1 year ago

TheTripleV commented 1 year ago

Currently, __hash__ = None results in a type checking error because it's original type is not optional. This PR changes that to __hash__ = None # type: None to force type checking to pass and the entire class is then correctly recognized as unhashable.

sizmailov commented 1 year ago

Thanks for PR!

The None-valued __hash__ can be safely removed from the stubs due to the following:

| A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None.

https://docs.python.org/3/reference/datamodel.html#object.__hash__

@TheTripleV Could you please update the PR?

TheTripleV commented 1 year ago

Thanks for the info. I made this PR to correct type hint detection in Pyright. Unfortunately, pyright only detects types as unhashable if they explicitly mark __hash__ as None.

I've opened an issue on that repo to see if the behavior there can be corrected: https://github.com/microsoft/pyright/issues/5446

TheTripleV commented 1 year ago

Neither mypy nor pyright currently have support for checking for hashability based on __eq__ and require explicit hints. I've updated the PR to use the convention that the Python Typeshed uses to mark classes explictly as unhashable.