CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-vine

Python promises library providing specialized promise-based asynchronous operations and lazy evaluation

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

Functional utilities for promise creation, modification, and composition. These utilities provide convenient ways to work with promises and enable advanced promise patterns.

Capabilities

Promise Creation Utilities

Utilities for creating and ensuring promises from various inputs.

def maybe_promise(p):
    """
    Return None if p is undefined, otherwise ensure it's a promise.
    
    Parameters:
    - p: any object that can be converted to a promise
    
    Returns:
    - None if p is falsy, otherwise a promise object
    """

def ensure_promise(p):
    """
    Ensure p is a promise, create empty promise if None.
    
    Parameters:
    - p: object to convert to promise, or None
    
    Returns:
    - promise object (empty promise if p was None)
    """

def starpromise(fun, *args, **kwargs):
    """
    Create promise using star arguments.
    
    Parameters:
    - fun: function for the promise
    - *args: positional arguments tuple
    - **kwargs: keyword arguments dict
    
    Returns:
    - promise object configured with the provided arguments
    """

Usage Examples:

from vine import maybe_promise, ensure_promise, starpromise

# maybe_promise - conditional promise creation
def handle_input(value):
    p = maybe_promise(value)  # None if value is falsy, promise otherwise
    if p:
        p.then(process_value)
    return p

# ensure_promise - guarantee promise object  
def chain_operation(callback):
    p = ensure_promise(callback)  # Creates empty promise if None
    return p.then(next_operation)

# Create pre-fulfilled promise manually
def get_cached_data():
    if cache_hit:
        p = promise(lambda: cached_value)
        p()  # Fulfill immediately
        return p
    else:
        return promise(fetch_from_database)

# starpromise - promise with star args
def async_math_operation():
    return starpromise(complex_calculation, 10, 20, method='fast')

Promise Modification Utilities

Utilities for modifying promise arguments and behavior.

def ppartial(p, *args, **kwargs):
    """
    Create/modify promise with partial arguments.
    
    Parameters:
    - p: promise to modify (created if None)
    - *args: positional arguments to prepend
    - **kwargs: keyword arguments to update
    
    Returns:
    - modified promise with combined arguments
    """

def preplace(p, *args, **kwargs):
    """
    Replace promise arguments completely.
    
    Forces promise to ignore fulfillment arguments and use provided args instead.
    
    Parameters:
    - p: promise to wrap
    - *args: replacement positional arguments
    - **kwargs: replacement keyword arguments
    
    Returns:
    - new promise that calls original with replacement arguments
    """

Usage Examples:

from vine import ppartial, preplace, promise

# ppartial - add arguments to existing promise  
def log_with_prefix(message, prefix="INFO"):
    print(f"{prefix}: {message}")

log_promise = promise(log_with_prefix)

# Add partial arguments
error_logger = ppartial(log_promise, prefix="ERROR")
error_logger("Something went wrong")  # Prints: ERROR: Something went wrong

# preplace - completely replace arguments
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet_promise = promise(greet)

# Force specific arguments regardless of how promise is called
spanish_greet = preplace(greet_promise, "Mundo", greeting="Hola")
result = spanish_greet("This will be ignored")  # Returns: "Hola, Mundo!"

Promise Transformation Utilities

Utilities for transforming promise results and chaining patterns.

def transform(filter_, callback, *filter_args, **filter_kwargs):
    """
    Filter/transform final argument to a promise through a transform function.
    
    Parameters:
    - filter_: function to transform the promise result
    - callback: target callback to receive transformed result
    - *filter_args: additional arguments for filter function
    - **filter_kwargs: additional keyword arguments for filter function
    
    Returns:
    - promise that applies filter to result before passing to callback
    """

def wrap(p):
    """
    Wrap promise to handle promise arguments specially.
    
    If called with a promise as argument, chains to that promise instead
    of treating it as a regular argument.
    
    Parameters:
    - p: promise to wrap
    
    Returns:
    - wrapped function that handles promise arguments
    """

Usage Examples:

from vine import transform, wrap, promise

# transform - filter promise results
def get_user_age(user_id, callback):
    # Transform the user object to extract just the age
    return fetch_user(user_id, transform(
        lambda user: user['age'],  # Filter function
        callback                   # Target callback
    ))

# More complex transform with additional arguments
def extract_and_convert(key, converter, data):
    return converter(data[key])

def get_page_expires(url, callback):
    return fetch_page_data(url, transform(
        extract_and_convert,       # Filter function
        callback,                  # Target callback  
        'expires',                 # Additional arg: key to extract
        converter=int              # Additional kwarg: conversion function
    ))

# wrap - handle promise arguments specially
def processor(data):
    return f"Processed: {data}"

wrapped_processor = wrap(promise(processor))

# Regular call
result1 = wrapped_processor("hello")  # Normal processing

# Promise argument - chains instead of processing the promise object
input_promise = promise(lambda: "async data")
result2 = wrapped_processor(input_promise)  # Chains to input_promise
input_promise()  # Triggers chain

Advanced Usage

Complex Promise Composition

from vine import *

def build_processing_pipeline():
    # Create base operations
    validate = promise(validate_data)
    transform_op = promise(transform_data)
    save = promise(save_to_database)
    
    # Compose complex pipeline
    def process_with_logging(data):
        # Add logging to each step
        logged_validate = ppartial(validate, logger=logger)
        
        # Transform result before saving
        filtered_save = transform(
            lambda result: {'processed': result, 'timestamp': time.now()},
            save
        )
        
        # Chain operations
        return logged_validate(data).then(transform_op).then(filtered_save)
    
    return process_with_logging

Dynamic Promise Building

def build_conditional_promise(condition, success_func, failure_func):
    if condition:
        return ensure_promise(success_func)
    else:
        # Create promise that immediately fails
        p = promise()
        p.throw(ValueError("Condition not met"))
        return p

# Usage
def fetch_user_data(user_id, has_permission):
    fetch_promise = build_conditional_promise(
        has_permission,
        lambda: fetch_from_database(user_id),
        lambda: "Access denied"
    )
    
    return fetch_promise

Promise Argument Manipulation

# Create a promise that always gets the same arguments
def create_fixed_args_promise(func, *fixed_args, **fixed_kwargs):
    base_promise = promise(func)
    return preplace(base_promise, *fixed_args, **fixed_kwargs)

# Create a promise with dynamic argument modification
def create_enhanced_promise(func, enhancer):
    def enhanced_func(*args, **kwargs):
        enhanced_args, enhanced_kwargs = enhancer(args, kwargs)
        return func(*enhanced_args, **enhanced_kwargs)
    
    return promise(enhanced_func)

# Usage
def add_timestamp_to_args(args, kwargs):
    return args + (time.now(),), kwargs

timestamped_logger = create_enhanced_promise(log_message, add_timestamp_to_args)

Install with Tessl CLI

npx tessl i tessl/pypi-vine

docs

abstract.md

index.md

promises.md

synchronization.md

utilities.md

tile.json