Replies: 1 comment 6 replies
-
I don't see a better solution than the one you've proposed. Most descriptors that don't support access through the class return |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm trying to type a descriptor that raises an error when accessed on the class instead of on an instance. Somewhat simplified example:
Simply removing
None
from the signature doesn't work sinceNone
is compatible withobject
anyway, but if the descriptor is only supposed to be used with a certain base class it's possible to substitute in that to rejectNone
. This solution works in my case and works okay in Mypy and Pyright (though the error message isn't the most obvious unless you understand how descriptors work):https://mypy-play.net/?mypy=latest&python=3.11&gist=03db7ed46920f565c295487e6595e904
https://pyright-play.net/?code=GYJw9gtgBALgngBwJYDsDmUkQWEMoAqiApgGoCGIANFAOLErEhIDGNYAbkwDZjkAmAWABQIglAC8hEhRAAKAEQEFAShEiW3cgGdtUAEI7iALigA6C%2BuGadegGJJi3fnPqNmLANoEAuiuMiUEFQHOTcAK4mhIHBMUH8xMBQAPrJqEgwqXLaTsA0oRFRBCpQALQAfFAAcmCMAcLBjVA53MBmBZGSIWGRcVB9CUmpaMSZydm57ABGAFamhjnsAO7upvAIxJ4LxH5llQT1TcFISWCzmHo1dX1HQSDkSDlQAIIwMMxT4TDEAKIg4PI1A1biBRuEQChmrl2j1iFYbLooHYwGA5Nt-H1yF0HE4XABmIGNKygrhhZLrYhyZFgMzkIEk4hkilUlFyFS0lRAA
If you don't have such a base class, another possibility is to add a overload for the
None
case that usesNoReturn
:https://mypy-play.net/?mypy=latest&python=3.11&gist=eeeaef24bca109c527630eea10be3134
https://pyright-play.net/?code=GYJw9gtgBALgngBwJYDsDmUkQWEMoAqiApgGoCGIANFAOLErEhIDGNYAbkwDZjkAmNAHJgASsRgBXECgCwAKAUEoAXkIkKIABQAiAjoCUChS27kAzuagAhC8QBcUAHQvj80xasAxJMW78tekZmFgBtAgBdA3sFKDioDnJuSQdCWPj0uP5iYCgAfTzUJBgCrXM-YBpE5NSCAygAWgA%2BKBFGGPl4rqhy7mAnapTVBKSUzKhxgAFOHj5%2BcezcgrQJUt7KqDAAIwArRzbidgB3YMd4BGJ65taxCWkURxcnKZmQXgEFnPy8lZK8soq7F2jm2O2ILBgx1OsBIVxaBEerk68UW31%2Ba0Bm2BWLBEKgAB8bowoUwzrDGvCOt14khcqDMFYDlTqd0QOQkOUoABBGAwZhbSQwYgAURA4G0RmR1JAdxkPQqA1GxDcHksUC8YDAWls5Wi43Iwx8fgCAGZJV03DKuEk8udiFoNWAnORJVbiDa7Q7NVoDM6DEA
A disadvantage of this approach is that it won't error at the attribute lookup site, but at the use site, and the error probably won't be that understandable in this case either.
What I would really like is to get the usual error that the attribute doesn't exist at all (e.g.
attr-defined
in Mypy). But that's perhaps not possible? Are there any other approaches that might be preferable to my suggestions?This part isn't directly related to type checking, but would also be nice with a solution which stopped IDEs from autocompleting the attribute on the class. Pylance still does in both cases at least.
Beta Was this translation helpful? Give feedback.
All reactions