Skip to main content

provides an intuitive API for building and manipulating Abstract Syntax Trees (ASTs) to generate Python code.

Project description

astlab

Latest Version Python Supported Versions MyPy Strict Test Coverage Downloads GitHub stars

astlab is a Python library that provides an intuitive API for building and manipulating Abstract Syntax Trees (ASTs) to generate Python code. With astlab, you can easily create Python modules, classes, fields, and more using a simple and readable syntax, and convert the AST back into executable Python code.

Features

  • Easy AST construction: Build Python code using a fluent and intuitive API.
  • Code generation: Convert your AST into valid Python code, forget about jinja templates.
  • Supports nested scopes & auto imports: Create nested classes, methods, and fields effortlessly. Reference types from other modules easily.
  • Highly customizable: Extend and modify the API to suit your needs.

Installation

You can install astlab from PyPI using pip:

pip install astlab

Usage

Simple example

Here's a basic example of how to use astlab to create a Python module with a dataclass.

import ast
import astlab

# Create a new Python module
with astlab.module("foo") as foo:
    # Build a "Bar" dataclass
    with foo.class_def("Bar").dataclass() as bar:
        # Define a field "spam" of type int
        bar.field_def("spam", int)

# Generate and print the Python code from the AST
print(foo.render())
# Or you can just get the AST
print(ast.dump(foo.build(), indent=4))

Output

Render:

import builtins
import dataclasses

@dataclasses.dataclass()
class Bar:
    spam: builtins.int

Dump built AST:

Module(
    body=[
        Import(
            names=[
                alias(name='builtins')]),
        Import(
            names=[
                alias(name='dataclasses')]),
        ClassDef(
            name='Bar',
            bases=[],
            keywords=[],
            body=[
                AnnAssign(
                    target=Name(id='spam'),
                    annotation=Attribute(
                        value=Name(id='builtins'),
                        attr='int'),
                    simple=1)],
            decorator_list=[
                Call(
                    func=Attribute(
                        value=Name(id='dataclasses'),
                        attr='dataclass'),
                    args=[],
                    keywords=[])])],
    type_ignores=[])

Func def & call example

import astlab

with astlab.module("foo") as foo:
    with foo.class_def("Bar") as bar:
        with bar.method_def("do_stuff").arg("spam", int).returns(str) as stuff:
            stuff.assign_stmt("result", stuff.call(str).arg(stuff.attr("spam")))
            stuff.return_stmt(stuff.attr("result"))

print(foo.render())

Output

import builtins

class Bar:

    def do_stuff(self, spam: builtins.int) -> builtins.str:
        result = builtins.str(spam)
        return result

Type reference example

import astlab

with astlab.package("main") as main:
    with main.module("foo") as foo:
        with foo.class_def("Bar") as bar:
            pass

    with main.module("spam") as spam:
        with spam.class_def("Eggs").inherits(bar) as eggs:
            with eggs.method_def("do_stuff").returns(bar.ref().optional()) as stuff:
                pass

print(spam.render())

Output

import main.foo
import typing

class Eggs(main.foo.Bar):

    def do_stuff(self) -> typing.Optional[main.foo.Bar]:
        pass

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

astlab-0.4.3.tar.gz (22.7 kB view details)

Uploaded Source

Built Distribution

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

astlab-0.4.3-py3-none-any.whl (26.2 kB view details)

Uploaded Python 3

File details

Details for the file astlab-0.4.3.tar.gz.

File metadata

  • Download URL: astlab-0.4.3.tar.gz
  • Upload date:
  • Size: 22.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for astlab-0.4.3.tar.gz
Algorithm Hash digest
SHA256 9b229f324a8161c28568c3e0edd3de61d56e727229a1f0aeb88f324e1ad784e2
MD5 ed5ad66170b928bea58eee5e4371acd9
BLAKE2b-256 ca9add9a760cfd308f1c767922283eacae57f2fb1fd51ffdd606c48b8b8a388a

See more details on using hashes here.

Provenance

The following attestation bundles were made for astlab-0.4.3.tar.gz:

Publisher: publish.yaml on zerlok/astlab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file astlab-0.4.3-py3-none-any.whl.

File metadata

  • Download URL: astlab-0.4.3-py3-none-any.whl
  • Upload date:
  • Size: 26.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for astlab-0.4.3-py3-none-any.whl
Algorithm Hash digest
SHA256 1383dffbc8a1dd2f89468fb57997228451ffe3f1a6fde0dd7a8661a4dda822ed
MD5 5811d511e57183e8056d82d49327af8a
BLAKE2b-256 f84648299f73d2d75a156d41c02c1c93235423330ffc352da10d89642cd34e80

See more details on using hashes here.

Provenance

The following attestation bundles were made for astlab-0.4.3-py3-none-any.whl:

Publisher: publish.yaml on zerlok/astlab

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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