Skip to main content

blockapily

blockapily is a Python utility that automatically generates Google Blockly assets from decorated class methods. It inspects a Python class and converts type-annotated methods into JavaScript block definitions, Python code generators, and toolbox XML.


Core Concept

The main idea is to keep your Python code as the single source of truth. You define the logic and parameters for an action in a Python method, add type hints, and use a simple decorator. blockapily then handles the boilerplate of creating the corresponding Blockly assets, ensuring they stay in sync with your Python implementation.


Quickstart

1. Define your Actions Class

Create a Python class and decorate the methods you want to expose in Blockly with @mced_block. Use standard type hints for parameters.

# my_robot.py
from blockapily import mced_block,mced_category

class Vec3:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        try:
            self.x = float(x)
            self.y = float(y)
            self.z = float(z)
        except (ValueError, TypeError):
            print(f"Warning: Invalid input for Vec3({x}, {y}, {z}). Defaulting to (0,0,0).")
            self.x = 0.0
            self.y = 0.0
            self.z = 0.0

@mced_category(name='Robot',colour='#222')
class RobotActions:
    """Defines actions a robot can perform."""

    @mced_block(label="Move Robot")
    def move(self, direction: Vec3, speed: float = 1.0, forward: bool = True):
        """A simple statement block."""
        pass

    @mced_block(label="Get Position")
    def get_position(self, target_id: int) -> Vec3:
        """A block that returns a value."""
        pass

2. Write your Generation Script

Create a script to run the generator. You only need to provide mappings for any custom types you used (like 'Vec3').

# generate_blocks.py
from pathlib import Path
from blockapily import BlocklyGenerator
from my_robot import RobotActions,Vec3

# 1. Define mappings for any custom types
CUSTOM_TYPE_MAP = {
            'str': 'String',
            'int': 'Number',
            'float': 'Number',
            'bool': 'Boolean',
            'Vec3': '3DVector'
}

CUSTOM_SHADOW_MAP = {
    'xml': {
        'int': '<shadow type="math_number"><field name="NUM">0</field></shadow>',
        'float': '<shadow type="math_number"><field name="NUM">0.0</field></shadow>',
        'str': '<shadow type="text"><field name="TEXT"></field></shadow>',
        'bool': '<shadow type="logic_boolean"><field name="BOOL">TRUE</field></shadow>',
        'Vec3': '<shadow type="vector_3d_zero"></shadow>'
    },
    'json': {
        'int': {'type': 'math_number', 'fields': {'NUM': 0}},
        'float': {'type': 'math_number', 'fields': {'NUM': 0.0}},
        'str': {'type': 'text', 'fields': {'TEXT': ''}},
        'bool': {'type': 'logic_boolean', 'fields': {'BOOL': 'TRUE'}},
        'Vec3': {'type': 'vector_3d_zero'}
    }
}

# 2. Instantiate the generator
generator = BlocklyGenerator(
    RobotActions,
    type_map=CUSTOM_TYPE_MAP,
    shadow_map=CUSTOM_SHADOW_MAP,
)

# 3. Generate the assets
block_defs_js, py_gen_js, toolbox_xml, toolbox_json = generator.generate()

# 4. Save the generated files
output_dir = Path("./generated_assets")
output_dir.mkdir(exist_ok=True)

(output_dir / "block_definitions.js").write_text(block_defs_js)
(output_dir / "python_generators.js").write_text(py_gen_js)

# 5. Update the main toolbox XML file
toolbox_path = output_dir / "toolbox.xml"
generator.update_toolbox(toolbox_xml, toolbox_path)
toolbox_path_json = output_dir / "toolbox.json"
generator.update_toolbox_json(toolbox_json, toolbox_path_json)

print(f"✅ Blockly assets generated in '{output_dir}'")

3. Run the Script

python generate_blocks.py

This will create a generated_assets directory containing your JavaScript files and an updated toolbox.xml ready to be used in your Blockly application.


Key Features

  • Decorator-based: Simply mark methods for export with a clear @mced_block decorator.
  • Type Hint Driven: Automatically infers Blockly types, shadows, and default values from standard Python type annotations.
  • Automatic Toolbox Management: Intelligently creates and updates your toolbox.xml and toolbox.json files, adding or replacing categories as needed.
  • Highly Configurable: Easily customize block prefixes, category names, colors, and mappings for custom types.

Metadata

Release files for blockapily 0.4.2

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

Source distribution (sdist)

Source distribution for blockapily 0.4.2
File Size Uploaded
blockapily-0.4.2.tar.gz 7.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for blockapily 0.4.2
File Interpreter ABI Platform
blockapily-0.4.2-py3-none-any.whl Python 3 none any Details

Total release size: 15.9 kB

Release files / blockapily-0.4.2.tar.gz

Download URL blockapily-0.4.2.tar.gz
Size 7.6 kB
Tags Source
SHA-256 checksum
How to use checksums
8f3e0a26e94f24a7f7d840a3dfd7c78102042931e03db6efc88d3845957a4be6
BLAKE2b-256 checksum
How to use checksums
a43236c04a02a56605a9333576b4b44d80e560561d0191def40cdfd5ff1619f7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / blockapily-0.4.2-py3-none-any.whl

Download URL blockapily-0.4.2-py3-none-any.whl
Size 8.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9290a103245f0713a88a61b71569baf3440fad6f3c6ad85acc4443e14dd7b85b
BLAKE2b-256 checksum
How to use checksums
e3a1f5b6f90f37de9f19527c4c243de0a55e270018c5f9722414a09ba22e0f7c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release history Release notifications | RSS feed

0.4.3

2 release files

This release

0.4.2 This release

2 release files

0.4.1

2 release files

0.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