weave.trace.op
Functions
TypedDict(typename, fields=None, /, *, total=True, **kwargs)
A simple typed namespace. At runtime it is equivalent to a plain dict.
TypedDict creates a dictionary type that expects all of its
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime but is only enforced by type checkers.
Usage::
class Point2D(TypedDict):
x: int
y: int
label: str
a: Point2D = {‘x’: 1, ‘y’: 2, ‘label’: ‘good’} # OK
b: Point2D = {‘z’: 3, ‘label’: ‘bad’} # Fails type check
assert Point2D(x=1, y=2, label=‘first’) == dict(x=1, y=2, label=‘first’)
The type info can be accessed via the Point2D.annotations dict, and
the Point2D.required_keys and Point2D.optional_keys frozensets.
TypedDict supports two additional equivalent forms::
Point2D = TypedDict(‘Point2D’, x=int, y=int, label=str)
Point2D = TypedDict(‘Point2D’, {‘x’: int, ‘y’: int, ‘label’: str})
By default, all keys must be present in a TypedDict. It is possible
to override this by specifying totality.
Usage::
class point2D(TypedDict, total=False):
x: int
y: int
This means that a point2D TypedDict can have any of the keys omitted.A type
checker is only expected to support a literal False or True as the value of
the total argument. True is the default, and makes all items defined in the
class body be required.
The class syntax is only supported in Python 3.6+, while two other
syntax forms work for Python 2.7 and 3.2+
aiter(obj: 'AsyncIterator[V]') -> 'AsyncIterator[V]'
No description available.
anext(obj: 'AsyncIterator[V]', default: 'V | None' = None) -> 'V'
No description available.
as_op(fn: 'Callable[P, R]') -> 'Op[P, R]'
Given a @weave.op() decorated function, return its Op.
@weave.op() decorated functions are instances of Op already, so this
function should be a no-op at runtime. But you can use it to satisfy type checkers
if you need to access OpDef attributes in a typesafe way.
Args:
fn: A weave.op() decorated function.
Returns:
The Op of the function.
call(op: 'Op', *args: 'Any', __weave: 'WeaveKwargs | None' = None, __should_raise: 'bool' = False, __require_explicit_finish: 'bool' = False, **kwargs: 'Any') -> 'tuple[Any, Call] | Coroutine[Any, Any, tuple[Any, Call]]'
Executes the op and returns both the result and a Call representing the execution.
This function will never raise. Any errors are captured in the Call object.
This method is automatically bound to any function decorated with @weave.op,
allowing for usage like:
calls(op: 'Op') -> 'CallsIter'
Get an iterator over all calls to this op.
This method is automatically bound to any function decorated with @weave.op,
allowing for usage like:
cast(typ, val)
Cast a value to a type.
This returns the value unchanged. To the type checker this
signals that the return value has the designated type, but at
runtime we intentionally don’t check anything (we want this
to be as fast as possible).
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class.
Examines PEP 526 annotations to determine fields.
If init is true, an init() method is added to the class. If
repr is true, a repr() method is added. If order is true, rich
comparison dunder methods are added. If unsafe_hash is true, a
hash() method function is added. If frozen is true, fields may
not be assigned to after instance creation.
get_captured_code(op: 'Op') -> 'str'
Get the captured code of the op.
This only works when you get an op back from a ref. The pattern is:
ref = weave.publish(func)
op = ref.get()
captured_code = op.get_captured_code()
get_raise_on_captured_errors() -> bool
No description available.
get_tracing_enabled() -> 'bool'
No description available.
is_op(obj: 'Any') -> 'TypeIs[Op]'
Check if an object is an Op.
is_placeholder_call(call: 'Call') -> 'TypeIs[NoOpCall]'
No description available.
is_tracing_setting_disabled() -> 'bool'
No description available.
log_once(log_method: 'Callable[[str], None]', message: 'str') -> 'None'
Logs a message once, suppressing subsequent messages of the same type. This
is useful for notifying the user about errors without spamming the logs.
This is mostly useful for cases where the same error message might occur many times.
For example, if an op fails to save, it is likely going to happen every time that op is
called. Or, if we have an error in our patched iterator, then it likely happens every time
we iterate over the result. This allows use to inform the user about the error without
clogging up their logs.
Args:
log_method: The method to use to log the message. This should accept a string argument.
message: The message to log.
Example:
maybe_bind_method(func: 'Callable', self: 'Any' = None) -> 'Callable | MethodType'
Bind a function to any object (even if it’s not a class).
If self is None, return the function as is.
maybe_unbind_method(oplike: 'Op | MethodType | partial') -> 'Op'
Unbind an Op-like method or partial to a plain Op function.
For:
- methods, remove set
selfparam - partials, remove any preset params
op(func: 'Callable[P, R] | None' = None, *, name: 'str | None' = None, call_display_name: 'str | CallDisplayNameFunc | None' = None, postprocess_inputs: 'PostprocessInputsFunc | None' = None, postprocess_output: 'PostprocessOutputFunc | None' = None, tracing_sample_rate: 'float' = 1.0, enable_code_capture: 'bool' = True, accumulator: 'Callable[[Any | None, Any], Any] | None' = None) -> 'Callable[[Callable[P, R]], Op[P, R]] | Op[P, R]'
A decorator to weave op-ify a function or method. Works for both sync and async.
Automatically detects iterator functions and applies appropriate behavior.
overload(func)
Decorator for overloaded functions/methods.
In a stub file, place two or more stub definitions for the same
function in a row, each decorated with @overload. For example:
@overload
def utf8(value: None) -> None: …
@overload
def utf8(value: bytes) -> bytes: …
@overload
def utf8(value: str) -> bytes: …
In a non-stub file (i.e. a regular .py file), do the same but
follow it with an implementation. The implementation should not
be decorated with @overload. For example:
@overload
def utf8(value: None) -> None: …
@overload
def utf8(value: bytes) -> bytes: …
@overload
def utf8(value: str) -> bytes: …
def utf8(value):
implementation goes here
placeholder_call() -> 'Call'
No description available.
setup_dunder_weave_dict(d: 'WeaveKwargs | None' = None) -> 'WeaveKwargs'
Sets up a __weave dict used to pass WeaveKwargs to ops.
should_skip_tracing_for_op(op: 'Op') -> 'bool'
No description available.
tracing_disabled() -> 'Iterator[None]'
No description available.
wraps(wrapped, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',))
Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
Classes
AsyncGenerator
No description available.Methods
aclose(self)
Raise GeneratorExit inside coroutine.
asend(self, value)
Send a value into the asynchronous generator.
Return next yielded value or raise StopAsyncIteration.
athrow(self, typ, val=None, tb=None)
Raise an exception in the asynchronous generator.
Return next yielded value or raise StopAsyncIteration.
AsyncIterator
No description available.Coroutine
No description available.Methods
close(self)
Raise GeneratorExit inside coroutine.
send(self, value)
Send a value into the coroutine.
Return next yielded value or raise StopIteration.
throw(self, typ, val=None, tb=None)
Raise an exception in the coroutine.
Return next yielded value or raise StopIteration.
DisplayNameFuncError
Inappropriate argument value (of correct type).Generator
No description available.Methods
close(self)
Raise GeneratorExit inside generator.
send(self, value)
Send a value into the generator.
Return next yielded value or raise StopIteration.
throw(self, typ, val=None, tb=None)
Raise an exception in the generator.
Return next yielded value or raise StopIteration.
Generic
Abstract base class for generic types. A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:: class Mapping(Generic[KT, VT]): def getitem(self, key: KT) -> VT: …Etc.
This class can then be used as follows:: def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return defaultIterator
No description available.Mapping
No description available.Methods
get(self, key, default=None)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
items(self)
D.items() -> a set-like object providing a view on D’s items
keys(self)
D.keys() -> a set-like object providing a view on D’s keys
values(self)
D.values() -> an object providing a view on D’s values
MethodType
method(function, instance) Create a bound instance method object.Op
The interface for Op-ified functions and methods. Op was previously a class, and has been converted to a Protocol to allow functions to pass for Op. This is needed because many popular packages are using theinspect module for control flow, and Op instances don’t always
pass those checks. In particular, inspect.iscoroutinefunction always
fails for classes, even ones that implement async methods or protocols.
Some of the attributes are carry-overs from when Op was a class. We should
consider removing the unnecessary ones where possible.
- resolve_fn (I think you can just use the func itself?)
- _set_on_output_handler (does this have to be on the op?)
- _on_output_handler (does this have to be on the op?)
Methods
_no_init(self, *args, **kwargs)
No description available.
OpCallError
Common base class for all non-exit exceptions.ParamSpec
Parameter specification variable. Usage:: P = ParamSpec(‘P’) Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable, a pattern commonly found in higher order functions and decorators. They are only valid when used inConcatenate,
or s the first argument to Callable. In Python 3.10 and higher,
they are also supported in user-defined Generics at runtime.
See class Generic for more information on generic types. An
example for annotating a decorator::
T = TypeVar(‘T’)
P = ParamSpec(‘P’)
def add_logging(f: Callable[P, T]) -> Callable[P, T]:
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f’{f.name} was called’)
return f(*args, **kwargs)
return inner
@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y
Parameter specification variables defined with covariant=True or
contravariant=True can be used to declare covariant or contravariant
generic types. These keyword arguments are valid, but their actual semantics
are yet to be decided. See PEP 612 for details.
Parameter specification variables can be introspected. e.g.:
P.name == ‘T’
P.bound == None
P.covariant == False
P.contravariant == False
Note that only parameter specification variables defined in global scope can
be pickled.