3 ms·
Along the lines of rewriting bytecode at runtime, https://www.python.org/dev/peps/pep-0302/ https://www.python.org/dev/peps/pep-0302/ lets you arbitrarily hook
by btown 5y ago
Along the lines of rewriting bytecode at runtime, https://www.python.org/dev/peps/pep-0302/ https://www.python.org/dev/peps/pep-0302/ lets you arbitrarily hook Python's import process and rewrite .pyc files as desired.
As a practical application, pytest uses this to take the statement `assert foo == bar` and rewrite the AST into a number of instructions that extract the values of foo and bar and print them if the assertion fails: http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests... (https://docs.pytest.org/en/6.2.x/assert.html https://docs.pytest.org/en/6.2.x/assert.html for those unfamiliar with the library) - so if you use pytest, you're already relying on these arcane techniques!
- pjmlp 5y agoBack in 1999 we used similar arcane techniques to ship encrypted Tcl scripts.
- AshamedCaptain 5y agoAnd probably still do the same today...
- borzunov 5y agoI do the same in my module that enables increment operators in Python by patching the bytecode for two unary plus/minus ops: https://github.com/borzunov/plusplus https://github.com/borzunov/plusplus