Skip to main content

Macro recording and metaprogramming in Python

Project description

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
  • 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)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

macro-kit-0.3.9.tar.gz (417.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

macro_kit-0.3.9-cp39-cp39-win_amd64.whl (355.5 kB view details)

Uploaded CPython 3.9Windows x86-64

File details

Details for the file macro-kit-0.3.9.tar.gz.

File metadata

  • Download URL: macro-kit-0.3.9.tar.gz
  • Upload date:
  • Size: 417.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.0 importlib_metadata/4.13.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.63.0 CPython/3.9.7

File hashes

Hashes for macro-kit-0.3.9.tar.gz
Algorithm Hash digest
SHA256 2837f1a0c1ddb91398c13e53a963adbb7e98a5d05fbde3e0d666fc3258bb2348
MD5 e843179ca868d29eaf93271a9564e5e5
BLAKE2b-256 6de70181eab5348c927847ac9153c4824853d71471fec4b3d52d9b010e517e1d

See more details on using hashes here.

File details

Details for the file macro_kit-0.3.9-cp39-cp39-win_amd64.whl.

File metadata

  • Download URL: macro_kit-0.3.9-cp39-cp39-win_amd64.whl
  • Upload date:
  • Size: 355.5 kB
  • Tags: CPython 3.9, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.0 importlib_metadata/4.13.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.63.0 CPython/3.9.7

File hashes

Hashes for macro_kit-0.3.9-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 a8d4e6f3ae87e05442711cd973326dba7e88b6aa8aed3d2afdb547ac2adf8dc7
MD5 7878c7e6c3478041c7e92395c3367e84
BLAKE2b-256 d637b1779870309e43293daecfb469af355942f8f33daad188479cadb2b4968f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page