A modern Python runtime for Forthic - a stack-based, concatenative programming language
Project description
Forthic Python Runtime
A Python runtime for Forthic - the stack-based, concatenative language for composable transformations.
Use Forthic to wrap your Python code within composable words, leveraging categorical principles for clean, powerful abstractions.
Learn at forthix.com | Forthic Docs | Getting Started | Examples | API Docs
What is Forthic?
Forthic enables categorical coding - a way to solve problems by viewing them in terms of transformation rather than computation. This Python runtime lets you:
- Wrap existing code with simple decorators
- Compose transformations cleanly using stack-based operations
- Build powerful abstractions from simple primitives
Learn more about Categorical Coding →
See the Forthic repository for technical documentation and API references.
Quick Example
Create a Module
from forthic.decorators import DecoratedModule, ForthicWord
class AnalyticsModule(DecoratedModule):
def __init__(self):
super().__init__("analytics")
@ForthicWord("( numbers -- avg )", "Calculate average")
async def AVERAGE(self, numbers):
return sum(numbers) / len(numbers)
@ForthicWord("( numbers stdDevs -- filtered )", "Filter outliers beyond N std devs")
async def FILTER_OUTLIERS(self, numbers, std_devs):
import statistics
mean = sum(numbers) / len(numbers)
std_dev = statistics.stdev(numbers)
threshold = std_dev * std_devs
return [n for n in numbers if abs(n - mean) <= threshold]
Use It
import asyncio
from forthic import Interpreter
async def main():
interp = Interpreter()
interp.register_module(AnalyticsModule())
await interp.run("""
["analytics"] USE-MODULES
[1 2 3 100 4 5] 2 FILTER-OUTLIERS AVERAGE
""")
result = interp.stack_pop() # Clean average without outliers
print(result)
asyncio.run(main())
Installation
Install from PyPI:
pip install forthic-py
Or for development:
cd forthic-py
pip install -e ".[dev]"
Getting Started
Basic Usage
import asyncio
from forthic import Interpreter
async def main():
interp = Interpreter()
# Execute Forthic code
await interp.run("""
[1 2 3 4 5] "2 *" MAP # Double each element
""")
result = interp.stack_pop() # [2, 4, 6, 8, 10]
print(result)
asyncio.run(main())
Creating Your First Module
from forthic.decorators import DecoratedModule, ForthicWord
class MyModule(DecoratedModule):
def __init__(self):
super().__init__("mymodule")
@ForthicWord("( data -- result )", "Process data your way")
async def PROCESS(self, data):
# Wrap your existing Python code
return my_existing_function(data)
# Register and use
async def main():
interp = Interpreter()
interp.register_module(MyModule())
await interp.run("""
["mymodule"] USE-MODULES
SOME-DATA PROCESS
""")
asyncio.run(main())
See examples/README.md for detailed tutorials and examples.
Features
Standard Library
The Python runtime includes comprehensive standard modules:
- array - MAP, SELECT, SORT, GROUP-BY, ZIP, REDUCE, FLATTEN (30+ operations)
- record - REC@, <REC, MERGE, KEYS, VALUES, INVERT-KEYS
- string - SPLIT, JOIN, UPPERCASE, LOWERCASE, TRIM, REPLACE
- math - +, -, *, /, ROUND, ABS, MIN, MAX, AVERAGE
- datetime - >DATE, >DATETIME, ADD-DAYS, FORMAT, DIFF-DAYS
- json - >JSON, JSON>, JSON-PRETTIFY
- boolean - ==, <, >, AND, OR, NOT, IN
See docs/modules/ for complete reference.
Pandas Integration
Python-specific module for DataFrame operations:
await interp.run("""
["pandas"] USE-MODULES
[
[ [.name "Alice"] [.age 30] ] REC
[ [.name "Bob"] [.age 25] ] REC
] DF-FROM-RECORDS
""")
Includes: DF-FROM-RECORDS, DF-TO-RECORDS, DF-SELECT, DF-SORT, DF-GROUP-BY, DF-READ-CSV, DF-TO-CSV, DF-READ-EXCEL, DF-TO-EXCEL
Easy Module Creation
The decorator system makes wrapping code trivial:
@ForthicWord("( input -- output )", "Description")
async def MY_WORD(self, input):
return your_logic(input)
Python Integration
- Full Python compatibility (Python 3.8+)
- Async/await support with
asyncio - Works with existing Python libraries
- Native Python error handling
Documentation
Learning Resources
- forthix.com - Learn about Forthic and Categorical Coding
- Category Theory for Coders - Understand the foundations
This Runtime
- Module API Reference - Standard library documentation
- Examples - Working code samples
Core Forthic Concepts
- Main Forthic Docs - Philosophy, language guide
- Why Forthic? - Motivation and core principles
- Category Theory - Mathematical foundations
- Building Modules - Module creation patterns
Examples
See the examples/ directory for working code samples including:
- Basic usage patterns
- Custom module creation
- Multi-runtime execution
- Pandas DataFrame integration
Building
# Install dependencies
pip install -e ".[dev]"
# Run all tests
pytest
# Run only unit tests
pytest tests/unit/
# Run only integration tests
pytest tests/integration/
# Run with coverage
pytest --cov=forthic
# Generate documentation
python -m scripts.generate_docs
Multi-Runtime Execution
Call code from other language runtimes seamlessly - use TypeScript's JavaScript libraries from Python, or Ruby's Rails from Python.
Quick Example
from forthic import Interpreter
from forthic.grpc.client import GrpcClient
from forthic.grpc.remote_runtime_module import RemoteRuntimeModule
async def main():
interp = Interpreter()
# Register the remote runtime module
remote_runtime = RemoteRuntimeModule()
interp.register_module(remote_runtime)
await interp.run("""
# Connect to TypeScript runtime
"localhost:50052" CONNECT-RUNTIME
# Load TypeScript modules
["mytsmodule"] USE-TS-MODULES
# Now use TypeScript code from Python!
SOME-DATA TS-FUNCTION-CALL
""")
asyncio.run(main())
Approaches
- gRPC - Python ↔ TypeScript ↔ Ruby (fast, server-to-server)
- WebSocket - Browser ↔ Python (client-server)
Learn More
📖 Complete Multi-Runtime Documentation
- Overview - When and how to use multi-runtime
- gRPC Setup - Server and client configuration
- WebSocket Setup - Browser-compatible communication
- Configuration - YAML config and connection management
- Examples - Working code samples
Runtime Status: ✅ TypeScript, Python, Ruby | 🚧 Rust | 📋 Java, .NET
Project Structure
forthic-py/
├── forthic/ # Core library code
│ ├── decorators/ # Decorator system for modules and words
│ ├── modules/ # Standard library modules
│ │ ├── standard/ # Standard modules (array, string, math, etc.)
│ │ └── pandas/ # Python-specific pandas integration
│ ├── grpc/ # gRPC client/server for multi-runtime
│ ├── websocket/ # WebSocket support
│ ├── interpreter.py # Main interpreter implementation
│ ├── module.py # Module and word classes
│ ├── tokenizer.py # Lexical analysis
│ └── errors.py # Error classes
├── tests/ # Test suite
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests
├── scripts/ # Utility scripts
│ └── generate_docs.py # Documentation generator
├── protos/ # Protocol buffer definitions
│ └── v1/ # Version 1 of gRPC protocol
└── docs/ # Generated documentation (created by generate_docs.py)
Cross-Runtime Compatibility
This Python implementation maintains compatibility with:
- forthic-ts (TypeScript/JavaScript)
- forthic-rb (Ruby)
- forthic-rs (Rust, in progress)
All runtimes share the same test suite and language semantics to ensure consistent behavior across platforms.
Contributing
See CONTRIBUTING.md for development guidelines, or refer to the main Forthic contributing guide.
When adding new words or modules:
- Use the decorator system (
@ForthicWordor@DirectWord) - Include stack effect notation:
( input -- output ) - Provide clear descriptions
- Add corresponding tests in
tests/ - Regenerate documentation:
python -m scripts.generate_docs
Community
- Main Repository: forthix/forthic
- Issues: Report issues
- Discussions: GitHub Discussions
- Examples: Real-world applications
License
BSD-2-Clause License - Copyright 2024 LinkedIn Corporation. Copyright 2025 Forthix LLC.
Related
- Forthic (main repo) - Core documentation and concepts
Forthic: Wrap. Compose. Abstract.
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
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file forthic_py-0.5.0.tar.gz.
File metadata
- Download URL: forthic_py-0.5.0.tar.gz
- Upload date:
- Size: 143.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c03b912ecab314235f935ecb500e96a9f56c2d0fb0cd90ac4668ed892d9432db
|
|
| MD5 |
8bf97941b090840d617cf0a0a2d2d6a7
|
|
| BLAKE2b-256 |
988f53edfc074ebd5058c9530da2968b9c4b5b6190193cb6e8d13da3a63a359a
|
File details
Details for the file forthic_py-0.5.0-py3-none-any.whl.
File metadata
- Download URL: forthic_py-0.5.0-py3-none-any.whl
- Upload date:
- Size: 82.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
83f2d8bdee68a9e43e9545671d498280802abd4dfaafffca67da97f51684dbb1
|
|
| MD5 |
aa542a4c1f039593a7d2ec1b13ab47c9
|
|
| BLAKE2b-256 |
31acdb2bb3b6bff91129debe91b46c8ee15b9fd299908298ed2e45967c0551b2
|