Skip to main content

License BSD-3 Python package index download statistics PyPI version Conda version

macro-kit

macro-kit is a package for efficient macro recording and metaprogramming in Python using abstract syntax tree (AST).

The design of AST in this package is strongly inspired by Julia metaprogramming. Similar methods are also implemented in builtin ast module but macro-kit (Julia-style metaprogramming) is more convenient in code operation and also focused on the macro generation and customization.

Installation

  • use pip
pip install macro-kit -U
  • from source
pip install git+https://github.com/hanjinliu/macro-kit

Examples

  1. Define a macro-recordable function
from macrokit import Macro, Expr, Symbol
macro = Macro()

@macro.record
def str_add(a, b):
    return str(a) + str(b)

val0 = str_add(1, 2)
val1 = str_add(val0, "xyz")
macro
[Out]
var0x24fdc2d1530 = str_add(1, 2)
var0x24fdc211df0 = str_add(var0x24fdc2d1530, 'xyz')

Use format method to rename variable names.

# substitute identifiers of variables
# var0x24fdc2d1530 -> x
macro.format([(val0, "x")])
[Out]
x = str_add(1, 2)
var0x24fdc211df0 = str_add(x, 'xyz')

format also support substitution with more complicated expressions.

# substitute to _dict["key"]
expr = Expr(head="getitem", args=[Symbol("_dict"), "key"])
macro.format([(val0, expr)])
[Out]
_dict['key'] = str_add(1, 2)
var0x24fdc211df0 = str_add(_dict['key'], 'xyz')
  1. Record class
macro = Macro()

@macro.record
class C:
    def __init__(self, val: int):
        self.value = val

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, new_value: int):
        if not isinstance(new_value, int):
            raise TypeError("new_value must be an integer.")
        self._value = new_value

    def show(self):
        print(self._value)

c = C(1)
c.value = 5
c.value = -10
c.show()
[Out]
-10

Note that value assignments are not recorded in duplicate.

macro.format([(c, "ins")])
[Out]
ins = C(1)
ins.value = -10
var0x7ffed09d2cd8 = ins.show()

eval can evaluate macro.

macro.eval({"C": C})
[Out]
-10
  1. Record module
import numpy as np
macro = Macro()
np = macro.record(np)  # macro-recordable numpy

arr = np.random.random(30)
mean = np.mean(arr)

macro
[Out]
var0x2a0a2864090 = numpy.random.random(30)
var0x2a0a40daef0 = numpy.mean(var0x2a0a2864090)

Recorded module is stored in Symbol so you can safely eval the macro without passing the module object as the global variables.

macro.eval()  # this works
  1. String parsing

parse calls ast.parse inside so that you can safely make Expr from string.

from macrokit import parse

expr = parse("result = f(0, l[2:8])")
expr
[Out]
:(result = f(0, l[slice(2, 8, None)]))
print(expr.dump())
[Out]
head: assign
args:
 0: result
 1: head: call
    args:
     0: f
     1: 0
     2: head: getitem
        args:
         0: l
         1: slice(2, 8, None)

Release files for macro-kit 0.4.10

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for macro-kit 0.4.10
File Size Uploaded
macro_kit-0.4.10.tar.gz 29.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for macro-kit 0.4.10
File Interpreter ABI Platform
macro_kit-0.4.10-py3-none-any.whl Python 3 none any Details

Total release size: 63.3 kB

Release files / macro_kit-0.4.10.tar.gz

Download URL macro_kit-0.4.10.tar.gz
Size 29.7 kB
Tags Source
SHA-256 checksum
How to use checksums
cb78a0ba35ab1c2090ba49c1f211037bf95cc0d72433d5fdb0823fefaf4c47f0
BLAKE2b-256 checksum
How to use checksums
3fd9d91e2616cf5945c9af5f01a525ab0538c529759af8cc272a83056ec0c03b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-httpx/0.27.2

Release files / macro_kit-0.4.10-py3-none-any.whl

Download URL macro_kit-0.4.10-py3-none-any.whl
Size 33.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
704dafa7bba6ddea40963f0e6fb7a3b8d56adf2a509fcbd90e8cdfa4369931cd
BLAKE2b-256 checksum
How to use checksums
14bdddda5dbf8d3f2fcadba02b256a9f3a3f19838c3dbb3efcef7cfab11e391c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-httpx/0.27.2

Release history Release notifications | RSS feed

This release

0.4.10 This release

2 release files

0.4.9

2 release files

0.4.8

2 release files

0.4.7

2 release files

0.4.6

2 release files

0.4.5

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

1 release file

0.4.0

2 release files

0.3.9

2 release files

0.3.8

2 release files

0.3.7

2 release files

0.3.6

2 release files

0.3.5

2 release files

0.3.4

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page