Use the .__args__
on your constructs. So the magic function you need is something like --
get_type_args = lambda genrc_type: getattr(genrc_type, '__args__')
My question is, how can I access these type arguments?
In situations like these -- how do I access ...
Use Python's powerful introspection features.
Even as a non-pro programmer I know I am trying to inspect stuff and dir
is a function which is like IDE in terminal. So after
>>> import typing
>>> str_to_bool_dict = typing.Dict[str, bool]
I want to see if there's anything that does the magic you want so
>>> methods = dir(str_to_bool_dict)
>>> methods
['__abstractmethods__', '__args__', .....]
I see too much info, to see if I am correct I verify
>>> len(methods)
53
>>> len(dir(dict))
39
Now let us find the methods which were designed specifically for generic types
>>> set(methods).difference(set(dir(dict)))
{'__slots__', '__parameters__', '_abc_negative_cache_version', '__extra__',
'_abc_cache', '__args__', '_abc_negative_cache', '__origin__',
'__abstractmethods__', '__module__', '__next_in_mro__', '_abc_registry',
'__dict__', '__weakref__'}
among these, __parameters__
, __extra__
, __args__
and __origin__
sound helpful. __extra__
and __origin__
won't work without self so we are left with __parameters__
and __args__
.
>>> str_to_bool_dict.__args__
(<class 'str'>, <class 'bool'>)
Hence the answer.
Introspection allows py.test
's assert
statements to make JUnit derived testing frameworks look obsolete. Even languages like JavaScript / Elm / Clojure don't have a straight-forward thingy like dir
of Python. Python's naming convention allows you to discover the language without actually reading (grokking in some cases such as these) the documentations.
So hunt using introspection and read documentation/mailing-lists to confirm your findings.
P.S. To OP -- this method also answers your question What's the correct way to check if an object is a typing.Generic? use discovery if you can't commit to mailing list or are a busy developer - that's the way to do it in python.