Superfunctions: A universal solution against sync/async fragmentation in Python
9 months ago
- #async-programming
- #python
- #code-generation
- The library 'transfunctions' helps avoid code duplication between sync and async functions in Python by using templates.
- Installation is done via pip: 'pip install transfunctions'.
- The '@transfunction' decorator allows creating templates that can generate sync, async, or generator functions.
- Context managers 'sync_context', 'async_context', and 'generator_context' define blocks specific to each function type.
- The 'get_usual_function()', 'get_async_function()', and 'get_generator_function()' methods generate respective function types from the template.
- Superfunctions, marked with '@superfunction', automatically adapt their behavior based on usage (sync, async, or generator).
- Superfunctions can be called with tilde syntax (~function()) for sync behavior, or via 'await'/'asyncio.run' for async behavior.
- The library operates at the AST level for code generation, ensuring global variable and closure access is preserved.
- Markers like 'await_it' are used to indicate where 'await' should be inserted in generated async functions.
- There are limitations, such as avoiding third-party decorators on templates and ensuring syntax correctness for generated functions.