New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ENH: Add Protocol for checking if a dtype is structured #22286
Comments
Note that the dtypes have a hierarchy,
Also, since
it would make sense to make that work for typing (if it doesn't already). Of course, not every |
well, that's cool if we use "isinstance" or "issubclass" instead of "np.issubdtype" |
I opened python/typing#1257 that would allow isinstance to check into fields if they are themselves Protocols. This would allow us to create a Protocol that can distinguish between a normal and structured dtype. # This is a Protocol for tuple, just to distinguish from None
@runtime_checkable
class _StructuredDTypeName(Protocol):
def count(self, value: Any) -> Any: ...
def index(self, start: int, stop: int) -> Any ...
# This is a Protocol for Mapping[str, tuple], just to distinguish from None
@runtime_checkable
class _StructuredDTypeFields(Protocol):
def get(self, key: str, default: str | None) -> Any: ...
... # more Mapping stuff
@runtime_checkable
class StructuredDType(Protocol):
@property
def names(self) -> _StructuredDTypeName: ...
@property
def fields(self) -> _StructuredDTypeFields: ... |
Yeah, you can use As Marten said, in theory, that is not correct because other dtypes can have fields. But even if that actually works in practice, I think we should get rid of it. (The use-case I know would be to have a C style EDIT: The isinstance check will work since NumPy 1.19, IIRC. Whoops, of course the isinstance check will also match unstructured voids or subarray dtypes unfortunately... |
String literals for structured dtypes are particularly tricky to deal with when static type checking (as pythons static typing tools lack any form of regex-based validation), so I strongly suspect that the right argument will simply be inferred as On the other hand, the As was pointed out previously this unfortuantely does not differentiate between the various flavors of |
Proposed new feature or change:
It would be very useful to be able to type annotate that a
dtype
is structured.A runtime-checkable
Protocol
is insufficient to detectnames
andfields
are notNone
in a structured dtype (https://docs.python.org/3/library/typing.html#typing.runtime_checkable).The text was updated successfully, but these errors were encountered: