Using Generic Type Constructors at Runtime

Hello all, I am working on an expression and replacement system in Python and am trying to figure out if constructors for generic classes should be done with classmethods or with functions. I have laid out an example using each in a Github issue (https://github.com/Quansight-Labs/metadsl/issues/69#issuecomment-500898932) and wanted to open the issue up the larger community because I am unsure if there is an established pattern here yet. A minimal example showing the difference is `none(int)` vs `Optional[int].none()`. (Note Optional here is not typing.Optional, but my own class). This has implications for the language, because if we want to support Optional[int].none() then we need to be able to access the generic type arguments at runtime which is currently impossible (without monkeypatching some typing internals) see https://github.com/python/typing/issues/629. But if we think the functional approach is more appropriate then we should be able to pass in TypeVars to functions at runtime, so we can define replacements on this form (see the linked issue above for the example). This would require fixing https://github.com/python/mypy/issues/6964. I would appreciate any thoughts on which is more Pythonic and more likely to continue being relevant as the typing conversation evolves. The underlying motivation is that Python is increasingly being used to build up computation that executes on other runtimes (TensorFlow, PyTorch, even if they try to hide it now) and type annotations give a nice UX for describing these APIs. We need to be able to inspect them at runtime to build up the right computation graphs, but we also want them to valid under static systems like MyPy, to continue using all the benefits it provides for dev productivity.

So I don't think python-dev is the best place to be asking this. For type-specific questions you probably want the typing-sig mailing list. For generic discussions you probably want python-list. (Based on how type-specific your question is I'm going to assume typing-sig might be the best place.) This mailing list is about the development _of_ Python and not _with_ Python.

OK I will post this on typing-sig. I was directed to post here instead of there because apparently that's more about static typing not runtime typing: https://github.com/python/typing/issues/629#issuecomment-494028130
participants (2)
-
Brett Cannon
-
Saul Shanabrook