Skip to main content

Go stdlib bindings for Python - Write Python, Get Go Speed

Project description

GOATED - Go stdlib for Python

PyPI version Python versions CI License: MIT

Write Python-like code. Get Go speeds.

GOATED exposes Go's entire standard library to Python through high-performance FFI bindings. Get the best of both worlds: Python's ease of use with Go's blazing speed.

Features

  • Go Speed: Native Go performance for CPU-intensive operations
  • Pythonic API: Three API styles to match your preferences
  • Type Safe: Full type hints with Result[T, E] error handling
  • Async Ready: Go channels integrate seamlessly with asyncio
  • Go Concurrency: Goroutines, WaitGroups, channels - just like Go
  • Free-threaded Ready: Optimized for Python 3.13t (no GIL) with true parallelism
  • Zero Dependencies: Uses only Python stdlib (ctypes)

Installation

pip install goated-py

Or build from source:

git clone https://github.com/Gaurav-Gosain/goated
cd goated
make install

Quick Start

Style A: Direct Mapping (Go names)

from goated.std import strings

# Split a string - returns GoSlice
result = strings.Split("hello,world,goated", ",")
print(result.to_list())  # ['hello', 'world', 'goated']

# Check containment
if strings.Contains("goated", "goat"):
    print("Found it!")

Style B: Pythonic Wrappers (snake_case)

from goated.pythonic import strings

# Returns native Python list
parts = strings.split("hello,world", ",")
print(parts)  # ['hello', 'world']

# Chainable operations with Result types
from goated.pythonic import strconv

value = strconv.parse_int("42", base=10).unwrap()
print(value)  # 42

# Handle errors gracefully
result = strconv.parse_int("not_a_number", base=10)
match result:
    case Ok(v):
        print(f"Parsed: {v}")
    case Err(e):
        print(f"Error: {e}")

Style C: Drop-in Replacement

# Use as drop-in replacement for Python stdlib
from goated.compat import json

data = json.loads('{"name": "goated", "fast": true}')
print(json.dumps(data, indent=2))

Error Handling with Result Types

GOATED uses Rust-inspired Result[T, E] types for elegant error handling:

from goated import Ok, Err, Result
from goated.std import strconv

def parse_config(raw: str) -> Result[int, Exception]:
    return strconv.Atoi(raw)

# Pattern matching (Python 3.10+)
match parse_config("42"):
    case Ok(value):
        print(f"Config value: {value}")
    case Err(error):
        print(f"Failed to parse: {error}")

# Fluent API
value = parse_config("42").unwrap_or(0)
doubled = parse_config("21").map(lambda x: x * 2).unwrap()

Go-style Concurrency

GOATED provides two concurrency models:

1. Sync Goroutines (Go-style)

Perfect for CPU-bound work and Go-style concurrency patterns:

from goated.runtime import go, WaitGroup, GoGroup, Chan, FastChan

# Simple goroutine spawning
go(lambda: print("Hello from goroutine!"))

# With WaitGroup (like Go's sync.WaitGroup)
wg = WaitGroup()
for i in range(10):
    wg.Add(1)
    go(worker, i, done=wg)
wg.Wait()  # Block until all done

# With GoGroup (easiest - automatic tracking)
with GoGroup() as g:
    for url in urls:
        g.go(fetch, url)
# Automatically waits here

# Channels for communication
ch = Chan[int](buffer=10)
go(lambda: [ch.Send(i) for i in range(10)] and ch.Close())
for val in ch:
    print(val)

# FastChan - alternative channel implementation
fast_ch = FastChan[int](buffer=1000)

Free-threaded Python (3.13t): The runtime automatically detects and optimizes for GIL-free execution:

from goated import is_free_threaded

if is_free_threaded():
    print("Running on free-threaded Python - true parallelism!")

2. Async Channels (asyncio integration)

Perfect for I/O-bound work and asyncio applications:

import asyncio
from goated import Channel, go

async def producer(ch: Channel[int]):
    for i in range(10):
        await ch.send(i)
    ch.close()

async def consumer(ch: Channel[int]):
    async for value in ch:
        print(f"Received: {value}")

async def main():
    ch = Channel[int](buffer_size=5)
    await asyncio.gather(
        producer(ch),
        consumer(ch)
    )

asyncio.run(main())

Available Packages

Package Status Description
strings Stable String manipulation
bytes Stable Byte slice operations
strconv Stable String conversions
encoding/json Stable JSON encoding/decoding
encoding/base64 Stable Base64 encoding
encoding/csv Stable CSV reading/writing
encoding/xml Stable XML parsing
crypto/sha256 Stable SHA-256 hashing
crypto/md5 Stable MD5 hashing
compress/gzip Stable Gzip compression
compress/zip Stable ZIP archive support
path Stable Path manipulation
path/filepath Stable OS-specific path operations
time Stable Time and duration handling
regexp Beta Regular expressions
net Beta Network operations
net/url Stable URL parsing
runtime Stable M:N goroutine scheduler, channels, sync primitives
goroutine Stable Go-style concurrency (WaitGroup, Chan, GoGroup)

See docs/std.md for the complete API reference.

Examples

The examples/ directory contains runnable examples demonstrating various features:

Example Description
basic_strings.py String manipulation basics
goroutines.py Go-style concurrency with WaitGroup and GoGroup
async_channels.py Async channels with asyncio integration
concurrent_patterns.py Common concurrency patterns (fan-out, pipeline, worker pool)
result_types.py Error handling with Result[T, E] types
json_processing.py JSON encoding/decoding
csv_etl.py CSV processing and ETL workflows
file_compression.py Gzip and ZIP compression
hashing_crypto.py Cryptographic hashing (SHA256, MD5)
filepath_os.py File path operations
http_client.py HTTP client usage
pipeline.py Data pipeline patterns
task_queue.py Task queue implementation
web_scraper.py Concurrent web scraping
templating.py Text templating

Run any example with:

uv run python examples/basic_strings.py

Benchmarks

Operation               Python      Goated      Speedup
-------------------------------------------------------
JSON parse (1MB)        45.2ms      8.1ms       5.6x
SHA256 (10MB)           89.3ms      12.4ms      7.2x
Gzip compress (5MB)     234ms       41ms        5.7x
String split (1M ops)   1.2s        0.18s       6.7x
Regex match (100K)      890ms       95ms        9.4x

How It Works

  1. Go Shared Library: Go code compiled with -buildmode=c-shared
  2. Handle-Based FFI: No raw pointers cross the boundary (GC-safe)
  3. ctypes Binding: Zero-dependency Python FFI
  4. Code Generation: Bindings auto-generated from Go source

Development

# Setup
make dev

# Build
make build

# Test
make test

# Lint
make lint

Code Generator

GOATED includes a code generator that parses Go stdlib packages and generates FFI bindings automatically.

Building the Generator

make gen-build

Usage

# Show bindable functions in a package
make generator PKG=strings

# Generate Go FFI code
make generator PKG=strings GO_OUT=golib/strings_gen.go

# Generate Python bindings
make generator PKG=strings PY_OUT=goated/std/strings_gen.py

# Generate both
make generator PKG=bytes GO_OUT=golib/bytes_gen.go PY_OUT=goated/std/bytes_gen.py

Direct CLI Usage

cd generator
./goated-gen -pkg strings                    # List bindable functions
./goated-gen -pkg strings -go-out /tmp/x.go  # Generate Go code
./goated-gen -pkg strings -py-out /tmp/x.py  # Generate Python code

The generator:

  • Parses Go AST to extract exported functions
  • Filters to only FFI-compatible signatures (basic types, slices)
  • Generates Go CGO export functions
  • Generates Python ctypes bindings with docstrings

Contributing

Contributions welcome! See CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE for details.


GOATED: Because your Python deserves to be the Greatest Of All Time, Expedited and Developed.

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

goated_py-0.1.2.tar.gz (2.3 MB view details)

Uploaded Source

Built Distribution

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

goated_py-0.1.2-py3-none-any.whl (2.3 MB view details)

Uploaded Python 3

File details

Details for the file goated_py-0.1.2.tar.gz.

File metadata

  • Download URL: goated_py-0.1.2.tar.gz
  • Upload date:
  • Size: 2.3 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for goated_py-0.1.2.tar.gz
Algorithm Hash digest
SHA256 3c34f348cc8aaeef699943830da83455a69be04d840308d27473e047c386b6a3
MD5 3c5aa9a279d6dcdb0fa1c423c3be73b0
BLAKE2b-256 d41db12eeb5eedd22541a0359da222a4304c939cbee4c4345b188102abcf756e

See more details on using hashes here.

Provenance

The following attestation bundles were made for goated_py-0.1.2.tar.gz:

Publisher: release.yml on Gaurav-Gosain/goated

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

File details

Details for the file goated_py-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: goated_py-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 2.3 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for goated_py-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 fbf23127060115ad74e3812fff46296cf30460e81046f15527579d3a0da0a15a
MD5 3a5186178c5dc97b00d9a818cd68eb1a
BLAKE2b-256 08320db3df7609f7f34da2aff4aa2eec6e4848f0737e4d4be5517180bb91123d

See more details on using hashes here.

Provenance

The following attestation bundles were made for goated_py-0.1.2-py3-none-any.whl:

Publisher: release.yml on Gaurav-Gosain/goated

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