PEP 718: subscriptable functions - #42 by Gobot1234 Fair as it’s not in pep at moment. The pep discussion includes comment by author on follow up draft pep to include runtime access of the generic argument. I think that pep is stronger if runtime access is included together but I understand the bigger pep gets the more work it is to implement in one step.
I’m mostly viewing it as in say few years from now, would type system both for static type checkers like mypy and runtime libraries like trycast find it preferable to have TypeForm or to have subscriptable functions with runtime access.
Edit: One note a name though is not really necessary. For generic classes there exists way today to access type arguments with dunders like __orig_class__
which works as type arguments are tuple and the only way to subscript today is positionally.
Edit 2: Also it is possible with 718 by itself to be enough. Use inspect part of standard library to find parent stack frame and extract back out the type argument. That will mostly work although it’ll have interesting edge cases/corners. I’d prefer a more obvious supported way but evaluating forward refs today across namespaces I already sometimes do similar trick of finding parent stack frame and saving it’s globals/locals for later type evaluation.
Edit 3: A few too many edits. def trycast[form: T](...)
is already legal syntax today. Although I’d guess it’d probably be written without : T part as that’s normally for bound. That syntax was added by type parameter syntax pep.