You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Using typing.Any to register a structure hook for a generic type is not working. #87
The reason is that typing.Any is not a class in that way. It actually just an alias (from the typing module):
Any = _SpecialForm('Any', doc='…')
And _SpecialForm is not the super class of any other class. If you do a subclass check, it will fail always:
>>>importtyping>>>issubclass(bool, typing.Any)
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>File"/home/raabf/.zplug/repos/pyenv/pyenv/versions/3.7.7/lib/python3.7/typing.py", line338, in__subclasscheck__raiseTypeError(f"{self} cannot be used with issubclass()")
TypeError: typing.Anycannotbeusedwithissubclass()
Or in other words, typing.Any can be only used for static type checks, but cattr.register_structure_hook() resolves the correct registered function by run-time type checking (issubclass/isinstance must succeed), hence it can never work.
Probably, registering typing.Any is a bad idea anyway, since it is a very generic type and hence unspecified to which type is should be constructed.
For your case you have two alternatives.
First, just define a class which purpose is to decide between specific types, for example:
importabcclassIntOrStrType(metaclass=abc.ABCMeta):
passdef_structure_int_or_str(d, t):
try:
returnint(d)
exceptAttributeError:
returnstr(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) # Trueissubclass(str, IntOrStrType) # Truecattr.register_structure_hook(IntOrStrType, _structure_int_or_str)
Then just use cattr.structure(some_input, IntOrStrType). This would also work with your generic types, but for generics there is an even better solution.
Second, if you want to have a single function for a generic class such as GenericList regardless which specific type it has, you can register the generic class as following:
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.lambdacls: issubclass(getattr(cls, '__origin__', bool), GenericList),
_structure_generic_list,
)
This will call _structure_generic_list always when GenericList or one of its subtypes is used, and the type T of the generic does not matter any more (so you can still use GenericList[str], GenericList[int], … as your attr type) .
Activity
raabf commentedon Aug 3, 2020
The reason is that
typing.Anyis not a class in that way. It actually just an alias (from the typing module):And
_SpecialFormis not the super class of any other class. If you do a subclass check, it will fail always:Or in other words,
typing.Anycan be only used for static type checks, butcattr.register_structure_hook()resolves the correct registered function by run-time type checking (issubclass/isinstance must succeed), hence it can never work.Probably, registering
typing.Anyis a bad idea anyway, since it is a very generic type and hence unspecified to which type is should be constructed.For your case you have two alternatives.
First, just define a class which purpose is to decide between specific types, for example:
Then just use
cattr.structure(some_input, IntOrStrType). This would also work with your generic types, but for generics there is an even better solution.Second, if you want to have a single function for a generic class such as
GenericListregardless which specific type it has, you can register the generic class as following:This will call
_structure_generic_listalways whenGenericListor one of its subtypes is used, and the typeTof the generic does not matter any more (so you can still use GenericList[str], GenericList[int], … as your attr type) .