Write compiled bytecode inline with standard Python syntax.
Project description
HAX lets you write compiled bytecode inline with pure Python. It was originally built for exploring new improvements to CPython's compiler and peephole optimizer.
Installation
HAX supports CPython 3.7+ on all platforms.
To install, just run:
$ pip install hax
Example
Consider the following function; it accepts a sequence of items, and returns a list with each item repeated twice:
def doubled(items):
out = []
for item in items:
out += item, item
return out
For example, doubled((0, 1, 2))
returns [0, 0, 1, 1, 2, 2]
.
We can make this function faster by keeping out
on the stack (instead of in a
local variable) and using the LIST_APPEND
op to build it. HAX makes it
simple to inline these instructions:
from hax import *
@hax
def doubled(items):
BUILD_LIST(0)
for item in items:
LOAD_FAST("item")
DUP_TOP()
LIST_APPEND(3)
LIST_APPEND(2)
RETURN_VALUE()
With the help of labeled jump targets (HAX_LABEL
), the function can be further
sped up by rewriting the for-loop in bytecode, removing all temporary
variables, and operating entirely on the stack:
from hax import *
@hax
def doubled(items):
BUILD_LIST(0)
LOAD_FAST("items")
GET_ITER()
HAX_LABEL("loop")
FOR_ITER("return")
DUP_TOP()
LIST_APPEND(3)
LIST_APPEND(2)
JUMP_ABSOLUTE("loop")
HAX_LABEL("return")
RETURN_VALUE()
It's important to realize that the functions HAX provides (BUILD_LIST
,
LOAD_FAST
, ...) aren't just "emulating" their respective bytecode
instructions; the @hax
decorator detects them, and completely recompiles
doubled
's code to use the actual ops that we've specified here!
These performance improvements are impossible to get from CPython's compiler and optimizer alone.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file hax-0.3.0.tar.gz
.
File metadata
- Download URL: hax-0.3.0.tar.gz
- Upload date:
- Size: 12.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.0 CPython/3.10.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b78835659e700075ac88492753d3e04d5fb5c1dfd6cf3a86bcb3c3bb3b0f96ac |
|
MD5 | f29d68dc6b60f9e5f9fe38e0b8a93e5a |
|
BLAKE2b-256 | f78a6cdaaab8c26df6b3c90895e819843a93673997e142823396056c9cb2e71b |
File details
Details for the file hax-0.3.0-py3-none-any.whl
.
File metadata
- Download URL: hax-0.3.0-py3-none-any.whl
- Upload date:
- Size: 12.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.0 CPython/3.10.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 615fe8f8edb1277a38a15dd5215d2eb6ac82f8decb405b48b7262f4db9f26332 |
|
MD5 | 756df02f63079ad5d59e1abf891d3b63 |
|
BLAKE2b-256 | b69ddb969bf2d0eee2b771415f49595815e5f2350e451947e28abc13c885f856 |