Skip to content
Advertisement

What’s the correct way to check if an object is a typing.Generic?

I’m trying to write code that validates type hints, and in order to do so I have to find out what kind of object the annotation is. For example, consider this snippet that’s supposed to tell the user what kind of value is expected:

JavaScript

This should print “value type should be one of (int, str)”, but instead it throws an exception:

JavaScript

isinstance doesn’t work either:

JavaScript

What’s the correct way to check if typ is a typing.Generic?

If possible, I would like to see a solution that’s backed by documentation or a PEP or some other resource. A “solution” that “works” by accessing undocumented, internal attributes is easy to find. But more likely than not, it’ll turn out to be an implementation detail and will change in future versions. I’m looking for “the right way” to do it.

Advertisement

Answer

As pointed out by sonny-garcia in the comments, get_origin() works from python 3.8

JavaScript

You can find more details in the docs

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement