Skip to main content

autocast

GitHub PyPI version License: MIT Python Versions

Automatic type conversion for Python.

autocast is a lightweight library that automatically converts objects from one type to another using a graph of registered transformation functions. If a direct conversion isn't available, autocast finds the shortest path through intermediate types to get you the result you need.

It comes with built-in support for NumPy, PyTorch, Open3D, and OmegaConf, but it is designed to be easily extensible for your own classes.

📦 Installation

pip install acaster

To install with support for all optional backends (PyTorch, Open3D, etc.):

pip install "acaster[all]"

🚀 Quick Start

Basic Usage

The core function is acast(object, target_type).

import torch
import numpy as np
from autocast import acast

# Create a Torch tensor
tensor = torch.ones((3, 3))

# Automatically convert to NumPy array
array = acast(tensor, np.ndarray)

print(type(array)) 
# <class 'numpy.ndarray'>

Advanced Usage (Open3D)

Build an Open3D Point Cloud directly from PyTorch tensors or Numpy arrays without manually converting them to Open3D Vector3dVector:

import open3d as o3d
import torch
from autocast import acast

H, W = 448, 448
rgb_image = torch.rand(H, W, 3) # H x W x 3
predicted_pts = torch.rand(H * W, 3) # H * W x 3 

# Cast a tuple of (points, colors) directly to a PointCloud
pcd = acast((predicted_pts, rgb_image), o3d.geometry.PointCloud)

print(type(pcd))
# <class 'open3d.cpu.pybind.geometry.PointCloud'> 

# o3d.io.write_point_cloud("output.ply", pcd)

Recursive Collection Handling

autocast automatically handles nested lists and dictionaries.

data = {
    "points": torch.rand(100, 3),
    "colors": torch.rand(100, 3),
    "meta": [torch.tensor(1.0), torch.tensor(2.0)]
}

# Convert everything inside the dict to NumPy arrays
numpy_data = acast(data, np.ndarray)

print(type(numpy_data['points'])) 
# <class 'numpy.ndarray'>

🛠 Features

  • Graph-Based Casting: Uses Breadth-First Search (BFS) to find conversion paths. If you have A -> B and B -> C, autocast can do A -> C automatically.
  • Zero-Overhead Imports: Backend modules (like torch or open3d) are only imported if they are installed in your environment.
  • Extensible: Register your own types and conversion functions easily.
From To Notes
torch.Tensor numpy.ndarray Zero-copy where possible
numpy.ndarray torch.Tensor
list/tuple np.ndarray
open3d.geometry numpy.ndarray Vector3dVector support
omegaconf.ListConfig list/dict Converts to native containers

🧩 Extending autocast

You can register your own casts using the add_acast function or the @acaster decorator.

Option 1: The Decorator

from autocast import acaster, acast

class Cat:
    def speak(self): return "Meow"

class Dog:
    def speak(self): return "Woof"

# Register a function that converts Cat -> Dog
@acaster(Cat, Dog)
def cat_to_dog(cat_instance):
    return Dog()

my_cat = Cat()
my_dog = acast(my_cat, Dog)

Option 2: Manual Registration

from autocast import add_acast

def str_to_int(s):
    return int(s)

add_acast(str, int, str_to_int)

print(acast("123", int)) # 123

🤝 Contributing

We welcome contributions! If you want to add support for a new library (e.g., Pandas, Polars, JAX), please submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/new-cast)
  3. Commit your changes
  4. Push to the branch
  5. Open a Pull Request

To run the tests, install pytests and run python -m pytest.

Publishing (Maintainers Only)

To release a new version of acaster:

  1. Bump Version: Update version = "x.y.z" in pyproject.toml.
  2. Tag Release:
git tag v0.x.y
git push origin --tags
  1. Build & Upload:
rm -rf dist/
python -m build
twine upload dist/*

📄 License

Distributed under the MIT License. See LICENSE for more information.

Acknowledgements

The idea for this library was inspired by erezsh/autocast.

Metadata

Release files for acaster 1.0.1

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

Source distribution (sdist)

Source distribution for acaster 1.0.1
File Size Uploaded Provenance
acaster-1.0.1.tar.gz 7.5 kB Without provenance Details

Built distribution (wheel)

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

Total release size: 15.9 kB

Release files / acaster-1.0.1.tar.gz

Download URL acaster-1.0.1.tar.gz
Size 7.5 kB
Tags Source
SHA-256 checksum
How to use checksums
2c31013284a26b81ef50ae4b2aeaf714ed3f428b7d6384b5a59850336f7211ec
BLAKE2b-256 checksum
How to use checksums
a514a0775d3cb725dce701553880f3bc25ad87381e8e46bbae4bf5bdcb84fb9a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.19

Release files / acaster-1.0.1-py3-none-any.whl

Download URL acaster-1.0.1-py3-none-any.whl
Size 8.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
161a309d84b3f858f548e823f4e7b1e5aaa77f79ed9cb43f33434ed8100c195e
BLAKE2b-256 checksum
How to use checksums
21d2618b83497dd6fca60588392c9b9e125dbcf1de7f84e1ef9554145ef4f6fa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.19

Security for acaster 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

1.0.1 This release

2 release files No provenance

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