-
-
Notifications
You must be signed in to change notification settings - Fork 118
Using typing.Any
to register a structure hook for a generic type is not working.
#87
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
Comments
The reason is that
And >>> import typing
>>> issubclass(bool, typing.Any)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/raabf/.zplug/repos/pyenv/pyenv/versions/3.7.7/lib/python3.7/typing.py", line 338, in __subclasscheck__
raise TypeError(f"{self} cannot be used with issubclass()")
TypeError: typing.Any cannot be used with issubclass() Or in other words, Probably, registering For your case you have two alternatives. First, just define a class which purpose is to decide between specific types, for example: import abc
class IntOrStrType(metaclass=abc.ABCMeta):
pass
def _structure_int_or_str(d, t):
try:
return int(d)
except AttributeError:
return str(d)
# Register the types is not required by cattr, but nice if you want to do check afterwards if the constructed value is a subtype of the attr field (for example some_words/some_ids in your example).
IntOrStrType.register(int)
IntOrStrType.register(str)
issubclass(int, IntOrStrType) # True
issubclass(str, IntOrStrType) # True
cattr.register_structure_hook(IntOrStrType, _structure_int_or_str) Then just use Second, if you want to have a single function for a generic class such as cattr.register_structure_hook_func(
# the default value (here `bool`) must be something so that the expression is `False` (i.e. not a subclass of GenericList). Could
# be also replaced by an `if hasattr(cls, '__origin__') …` but it is shorter and faster that way.
# The object has a __origin__ attribute if it us used as `Class[TYPE]`, then __origin__ will point to `Class`. This
# test is secure enough since it is not only tested that the class has the attribute, but that it is also
# a subclass of GenericList, which is the class we want to support with this converter.
lambda cls: issubclass(getattr(cls, '__origin__', bool), GenericList),
_structure_generic_list,
) This will call |
Description
Using
typing.Any
to register a structure hook for a generic type is not working.The text was updated successfully, but these errors were encountered: