Skip to main content

from tramp.as_completed import AsCompleted

Tramp

A collection of useful utilities that can be used in any project.

Installation

pip install tramp

Annotations

A utility for evaluating string annotations with support for forward references when a name cannot be evaluated. Forward references can be evaluated later by calling the forward reference's evaluate method. This is a similar API to PEP 649, although it is not fully compatible and only emulates the behavior of Format.FORWARDREF. Certain things are not possible (at least not without some serious hacking) such as using ForwardRef instances as that would break many annotation types from the typing module. To help with this limitation the tramp.annotations.ForwardRefMeta type overrides the isinstance check to return True when Tramp's version of the ForwardRef class is used in an instance check (isinstance or a match/case). The goal is to implement the most essential parts of the PEP to begin reaping the benefits of forward references now with the least necessary refactoring later.

On Python 3.14 Tramp falls through to the PEP 649 implementation.

from tramp.annotations import get_annotations


class Foo:
    bar: "Bar"


annotations = get_annotations(Foo)  # {'bar': <ForwardRef 'Bar'>}


class Bar:
    pass


annotations["bar"].evaluate()  # <class '__main__.Bar'>

It supports generic types, metadata, function calls/class instantiation, etc.

class Foo:
    bar: "list[int]"
    baz: "Callable[[int], str]"
    qux: "Annotated[int, Bar('baz')]"

As Completed

The AsCompleted type is a wrapper around asyncio.as_completed that adds an async iterator over the results from each task. This simplifies iterating over tasks, eliminating the need to await the next result.

from tramp.as_completed import AsCompleted
...
tasks = [...]
async for result in AsCompleted(*tasks):
    ...

Additionally it is possible to use AsCompleted in the same way that as_completed operates.

for next_result in AsCompleted(*tasks):
    result = await next_result

Async Batch Iterators

The AsyncBatchIterator type is an async iterator that yields results one at a time from batches. It takes a coroutine that returns batches at a batch index. The coroutine can return either a Iterable or an AsyncIterable. If the coroutine returns None or an empty batch, the batched iterator stops.

async def get_batch(batch_index: int) -> Iterable[int] | None:
    if batch_index > 1:
        return
    
    return range(batch_index * 2, (batch_index + 1) * 2)
    
async def main():
    async for result in AsyncBatchIterator(get_batch):
        print(result)

Containers

A container acts a reference to a changeable value.

from tramp.containers import Container

container = Container[int](0)
container.set(1)

print(container.value)  # 1

An empty container can also be created. Attempting to access the value raises a ValueError. The error can be avoided by using the value_or method or by checking the never_set boolean property.

Modules

Helper functions for working with modules

from tramp import modules
from typing import Any

ns: dict[str, Any] = modules.get_module_namespace("some_module")

Optionals

An optional type that can be used with match statements.

from tramp.optionals import Optional

def foo(x: int) -> Optional[int]:
    if x > 0:
        return Optional.Some(x)
        
    return Optional.Nothing()

result = foo(1)
print(result.value) # 1

result = foo(-1)
print(result.value) # Raises an exception

result = foo(-1)
print(result.value_or(0)) # 0

...

match foo(1):
    case Optional.Some(x):
        print(x)

    case Optional.Nothing():
        print("Nothing")

# Output: 1

match foo(-1):
    case Optional.Some(x):
        print(x)

    case Optional.Nothing():
        print("Nothing")

# Output: Nothing

Protected Strings

A protected string type that can be used to store sensitive information. The string is redacted when rendered into a string. The value can be accessed using the value property.

from tramp.protected_strings import ProtectedString

password = ProtectedString("password", name="password")
print(password)  # <Redacted>

print(f"Password: {password}")  # Password: <Redacted>
print(f"Password: {password.value}")  # Password: password
print(f"Password: {password:***}")  # Password: ***
print(f"Password: {password:***$password}")  # Password: password
print(f"Password: {password:$password}")  # Password: password

ProtectedStrings can be combined with other strings to create a ProtectedStringBuilder which can combine and format multiple protected strings with each other and normal strings.

from tramp.protected_strings import ProtectedString

foo = ProtectedString("Hello", name="foo")
bar = ProtectedString("World", name="bar")
builder = foo + " " + bar + "!!!"
print(f"{builder}")  # <Redacted Foo> <Redacted Bar>!!!
print(f"{builder:***}")  # *** ***!!!
print(f"{builder:$foo}")  # Hello <Redacted Bar>!!!
print(f"{builder:***$foo}")  # Hello ***!!!
print(f"{builder:$foo,bar}")  # Hello World!!!
print(f"{builder:***$foo,bar}")  # Hello World!!!

Results

A result type that can be used with match statements. Works the same as Optionals with an added error property.

from tramp.results import Result

with Result.build() as result:
    result.value = 1

print(result.value) # 1
print(result.error) # None

with Result.build() as result:
    raise Execption("Error")

print(result.value) # Raises an exception
print(result.value_or(0)) # 0
print(result.error) # Exception("Error")

Sentinel

A sentinel value that can be used to represent a unique value. Useful for creating NotSet types. Instantiating any sentinel type will always return the same singleton instance of that type allowing for is checks.

from tramp.sentinels import sentinel

NotSet = sentinel("NotSet")


def foo(x: int | NotSet = NotSet()) -> int:
    if x is NotSet():
        return 0

    return x

Metadata

Release files for tramp 2025.3.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 tramp 2025.3.2
File Size Uploaded Provenance Actions
tramp-2025.3.2.tar.gz 12.2 kB Without provenance Details for tramp-2025.3.2.tar.gz

Built distribution (wheel)

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

Total release size: 24.3 kB

Release files / tramp-2025.3.2.tar.gz

Download URL tramp-2025.3.2.tar.gz
Size 12.2 kB
Tags Source
SHA-256 checksum
How to use checksums
e5fe77f1e59e05293bdb0ef694228d96c2d048060459cfc85a63da1a2dd4db92
BLAKE2b-256 checksum
How to use checksums
1d6574e4785130086a4f2ec1a790611bafc5d2016d5560a2581e01fc915971e6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.6.9

Release files / tramp-2025.3.2-py3-none-any.whl

Download URL tramp-2025.3.2-py3-none-any.whl
Size 12.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
90de5498a733e9415cf2c1396ba0989eb2140b18ac9b875f9a16659736011d97
BLAKE2b-256 checksum
How to use checksums
5acc1512973837510f7cf39fcb404b310b345b44f39a7b5d2089cd2e60634be9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.6.9

Security for tramp 2025.3.2

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.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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