Replies: 1 comment 1 reply
-
The problem here is that the type checker does not know the type of the type arguments for Presumably you have the It would be convenient if we could use a subscripted type in an if isinstance(obj, Mapping[Any, Any]): but this isn't legal at runtime. This is a rare case where I would probably resort to using a def unwrap(obj: Any) -> Any:
if isinstance(obj, Mapping):
return {
key: unwrap(value) for key, value in cast(Mapping[Any, Any], obj).items()
}
elif isinstance(obj, Sequence) and not isinstance(obj, (str, bytes)):
return [unwrap(item) for item in cast(Sequence[Any], obj)]
else:
return obj |
Beta Was this translation helpful? Give feedback.
-
I'm annotating a function that recursively processes items in a mapping/sequence structure, but I'm warned that the key and value types aren't known. With generics, and without the actual processing logic, I have the following:
Ideally the
isinstance()
checks would be sufficient to match the types from the corresponding overloads, but I'm guessing the presence ofAny
makes it ambiguous? What's the best way to match up the key/value types here?This could probably be fixed with the new
TypeGuard
, but that feels a bit unnecessary here.Beta Was this translation helpful? Give feedback.
All reactions