giving.gvn

class giving.gvn.Given(context=<ContextVar name='global_context' default=()>, _obs=None, _root=None)

Observable that streams the values given using give().

Instances of Given must be activated as a context manager in order to work, and each instance can only be activated once.

# Instantiate a Given and set up a pipeline of operations
gv = given()
gv["?x"].max().print("max(x) = {}")

# Calls to give() do nothing yet
give(x=12345)

# We activate gv using a ``with`` statement:
with gv:
    # NOW, calls to give() are fed into the pipeline
    give(x=1, y=1)

    # You can still add to the pipeline, but the new operations
    # will only pick up future calls to give()
    gv["?y"].min().print("min(y) = {}")

    give(x=2, y=2)
    ...

# min, max and other reductions are resolved after the block ends
# Prints max(x) = 2 (x=12345 is outside the block and ignored)
# and min(y) = 2 (y=1 is before the call to min()).

with gv:
    # ERROR because gv can only be activated once
    ...
Parameters

context – The ContextVar to use to sync with give.

accum(obj=None)

Accumulate into a list or set.

Parameters

obj – The object in which to accumulate, either a list or a set. If not provided, a new list is created.

Returns

The object in which the values will be accumulated.

breakpoint(**kwargs)

Trigger a breakpoint on every entry.

Parameters

skip – A list of globs corresponding to modules to skip during debugging, for example skip=["giving.*"] would skip all frames that are in the giving module.

breakword(**kwargs)

Trigger a breakpoint using breakword.

This feature requires the breakword package to be installed, and the tag() operator to be applied.

gvt = gv.tag()
gvt.display()
gvt.breakword()

The above will display words next to each entry. Set the BREAKWORD environment to one of these words to set a breakpoint when it is printed.

Parameters
  • skip – A list of globs corresponding to modules to skip during debugging, for example skip=["giving.*"] would skip all frames that are in the giving module.

  • word – Only trigger the breakpoint on the given word.

display(*, breakword=None, skip=[], **kwargs)

Pretty-print each element.

Parameters
  • colors – Whether to colorize the output or not.

  • time_format – How to format the time (if present), e.g. "%Y-%m-%d %H:%M:%S"

  • breakword – If not None, run self.breakword(word=breakword).

  • skip – If breakword is not None, pass skip to the debugger.

eval(fn, *args, **kwargs)

Run a function in the context of this Given and get the values.

def main():
    give(x=1)
    give(x=2)

values = given()["x"].eval(main)
assert values == [1, 2]
Parameters
  • fn – The function to run.

  • args – Positional arguments to pass to fn.

  • kwargs – Keyword arguments to pass to fn.

exec(fn, *args, **kwargs)

Run a function in the context of this Given.

def main():
    give(x=1)
    give(x=2)

gv = given()
gv["x"].print()
gv.exec(main)  # prints 1, 2
Parameters
  • fn – The function to run.

  • args – Positional arguments to pass to fn.

  • kwargs – Keyword arguments to pass to fn.

fail(message=None, exc_type=<class 'giving.gvn.Failure'>, skip=['giving.*', 'rx.*'])

Raise an exception if the stream produces anything.

Parameters
  • message – The exception message (format).

  • exc_type – The exception type to raise. Will be passed the next data element, and the result is raised. Defaults to Failure.

  • skip – Modules to skip in the traceback. Defaults to “giving.*” and “rx.*”.

fail_if_empty(message=None, exc_type=<class 'giving.gvn.Failure'>, skip=['giving.*', 'rx.*'])

Raise an exception if the stream is empty.

Parameters

exc_type – The exception type to raise. Defaults to Failure.

give(*keys, **extra)

Give each element.

This calls give() for each value in the stream.

Be careful using this method because it could easily lead to an infinite loop.

Parameters
  • keys – Key(s) under which to give the elements.

  • extra – Extra key/value pairs to give along with the rest.

ksubscribe(fn)

Subscribe a function called with keyword arguments.

Note

The function passed to ksubscribe is wrapped with lax_function(), so it is not necessary to add a **kwargs argument for keys that you do not need.

gv.ksubscribe(lambda x, y=None, z=None: print(x, y, z))
give(x=1, z=2, abc=3)  # Prints 1, None, 2
Parameters

fn – The function to call.

kwrap(name, fn=None, return_function=False)

Subscribe a context manager, corresponding to wrap().

obs.kwrap(fn) is shorthand for obs.wrap(fn, pass_keys=True).

Note

The function passed to ksubscribe is wrapped with lax_function(), so it is not necessary to add a **kwargs argument for keys that you do not need.

@gv.kwrap
def _(x):
    print(">", x)
    yield
    print("<", x)

with give.wrap(x=1):      # prints >1
    ...
    with give.wrap(x=2):  # prints >2
        ...
    ...                   # prints <2
...                       # prints <1
Parameters
  • name – The name of the wrap block to subscribe to.

  • fn – The wrapper function. The arguments to give.wrap are transferred to this function as keyword arguments.

pipe(*ops)

Pipe one or more operators.

Returns: An ObservableProxy.

print(format=None, skip_missing=False)

Print each element of the stream.

Parameters
  • format – A format string as would be used with str.format.

  • skip_missing – Whether to ignore KeyErrors due to missing entries in the format.

subscribe(observer=None, on_next=None, on_error=None, on_completed=None)

Subscribe a function to this Observable stream.

with given() as gv:
    gv.subscribe(print)

    results = []
    gv["x"].subscribe(results.append)

    give(x=1)  # prints {"x": 1}
    give(x=2)  # prints {"x": 2}

    assert results == [1, 2]
Parameters
  • observer – The object that is to receive notifications.

  • on_error – Action to invoke upon exceptional termination of the observable sequence.

  • on_completed – Action to invoke upon graceful termination of the observable sequence.

  • on_next – Action to invoke for each element in the observable sequence.

Returns

An object representing the subscription with a dispose() method to remove it.

values()

Context manager to accumulate the stream into a list.

with given()["?x"].values() as results:
    give(x=1)
    give(x=2)

assert results == [1, 2]

Note that this will activate the root given() including all subscriptions that it has (directly or indirectly).

wrap(name, fn=None, pass_keys=False, return_function=False)

Subscribe a context manager, corresponding to wrap().

@gv.wrap("main")
def _():
    print("<")
    yield
    print(">")

with give.wrap("main"):    # prints <
    ...
    with give.wrap("sub"):
        ...
    ...
...                        # prints >
Parameters
  • name – The name of the wrap block to subscribe to.

  • fn – The wrapper function OR an object with an __enter__ method. If the wrapper is a generator, it will be wrapped with contextmanager(fn). If a function, it will be called with no arguments, or with the arguments given to give.wrap if pass_keys=True.

  • pass_keys – Whether to pass the arguments to give.wrap to this function as keyword arguments. You may use kwrap() as a shortcut to pass_keys=True.

__or__(other)

Alias for merge().

Merge this ObservableProxy with another.

__rshift__(subscription)

Alias for subscribe().

If subscription is a list or a set, accumulate into it.

__getitem__(item)

Mostly an alias for getitem().

Extra feature: if the item starts with "?", getitem is called with strict=False.

The methods below are shortcuts to the corresponding operators in giving.operators, applied to self:

affix(...)

See affix()

all(...)

See all()

amb(...)

See amb()

as_(...)

See as_()

as_observable(...)

See as_observable()

augment(...)

See augment()

average(...)

See average()

average_and_variance(...)

See average_and_variance()

bottom(...)

See bottom()

buffer(...)

See buffer()

buffer_toggle(...)

See buffer_toggle()

buffer_when(...)

See buffer_when()

buffer_with_count(...)

See buffer_with_count()

buffer_with_time(...)

See buffer_with_time()

buffer_with_time_or_count(...)

See buffer_with_time_or_count()

catch(...)

See catch()

collect_between(...)

See collect_between()

combine_latest(...)

See combine_latest()

concat(...)

See concat()

contains(...)

See contains()

count(...)

See count()

debounce(...)

See debounce()

default_if_empty(...)

See default_if_empty()

delay(...)

See delay()

delay_subscription(...)

See delay_subscription()

delay_with_mapper(...)

See delay_with_mapper()

dematerialize(...)

See dematerialize()

distinct(...)

See distinct()

distinct_until_changed(...)

See distinct_until_changed()

do(...)

See do()

do_action(...)

See do_action()

do_while(...)

See do_while()

element_at(...)

See element_at()

element_at_or_default(...)

See element_at_or_default()

exclusive(...)

See exclusive()

expand(...)

See expand()

filter(...)

See filter()

filter_indexed(...)

See filter_indexed()

finally_action(...)

See finally_action()

find(...)

See find()

find_index(...)

See find_index()

first(...)

See first()

first_or_default(...)

See first_or_default()

flat_map(...)

See flat_map()

flat_map_indexed(...)

See flat_map_indexed()

flat_map_latest(...)

See flat_map_latest()

flatten(...)

See flatten()

fork_join(...)

See fork_join()

format(...)

See format()

getitem(...)

See getitem()

group_by(...)

See group_by()

group_by_until(...)

See group_by_until()

group_join(...)

See group_join()

group_wrap(...)

See group_wrap()

ignore_elements(...)

See ignore_elements()

is_empty(...)

See is_empty()

join(...)

See join()

keep(...)

See keep()

kfilter(...)

See kfilter()

kmap(...)

See kmap()

kmerge(...)

See kmerge()

kscan(...)

See kscan()

last(...)

See last()

last_or_default(...)

See last_or_default()

map(...)

See map()

map_indexed(...)

See map_indexed()

materialize(...)

See materialize()

max(...)

See max()

merge(...)

See merge()

merge_all(...)

See merge_all()

min(...)

See min()

multicast(...)

See multicast()

observe_on(...)

See observe_on()

on_error_resume_next(...)

See on_error_resume_next()

pairwise(...)

See pairwise()

partition(...)

See partition()

partition_indexed(...)

See partition_indexed()

pluck(...)

See pluck()

pluck_attr(...)

See pluck_attr()

publish(...)

See publish()

publish_value(...)

See publish_value()

reduce(...)

See reduce()

ref_count(...)

See ref_count()

repeat(...)

See repeat()

replay(...)

See replay()

retry(...)

See retry()

roll(...)

See roll()

sample(...)

See sample()

scan(...)

See scan()

sequence_equal(...)

See sequence_equal()

share(...)

See share()

single(...)

See single()

single_or_default(...)

See single_or_default()

single_or_default_async(...)

See single_or_default_async()

skip(...)

See skip()

skip_last(...)

See skip_last()

skip_last_with_time(...)

See skip_last_with_time()

skip_until(...)

See skip_until()

skip_until_with_time(...)

See skip_until_with_time()

skip_while(...)

See skip_while()

skip_while_indexed(...)

See skip_while_indexed()

skip_with_time(...)

See skip_with_time()

slice(...)

See slice()

some(...)

See some()

sole(...)

See sole()

sort(...)

See sort()

starmap(...)

See starmap()

starmap_indexed(...)

See starmap_indexed()

start_with(...)

See start_with()

subscribe_on(...)

See subscribe_on()

sum(...)

See sum()

switch_latest(...)

See switch_latest()

tag(...)

See tag()

take(...)

See take()

take_last(...)

See take_last()

take_last_buffer(...)

See take_last_buffer()

take_last_with_time(...)

See take_last_with_time()

take_until(...)

See take_until()

take_until_with_time(...)

See take_until_with_time()

take_while(...)

See take_while()

take_while_indexed(...)

See take_while_indexed()

take_with_time(...)

See take_with_time()

throttle(...)

See throttle()

throttle_first(...)

See throttle_first()

throttle_with_mapper(...)

See throttle_with_mapper()

throttle_with_timeout(...)

See throttle_with_timeout()

time_interval(...)

See time_interval()

timeout(...)

See timeout()

timeout_with_mapper(...)

See timeout_with_mapper()

timestamp(...)

See timestamp()

to_dict(...)

See to_dict()

to_future(...)

See to_future()

to_iterable(...)

See to_iterable()

to_list(...)

See to_list()

to_marbles(...)

See to_marbles()

to_set(...)

See to_set()

top(...)

See top()

variance(...)

See variance()

where(...)

See where()

where_any(...)

See where_any()

while_do(...)

See while_do()

window(...)

See window()

window_toggle(...)

See window_toggle()

window_when(...)

See window_when()

window_with_count(...)

See window_with_count()

window_with_time(...)

See window_with_time()

window_with_time_or_count(...)

See window_with_time_or_count()

with_latest_from(...)

See with_latest_from()

wmap(...)

See wmap()

zip(...)

See zip()

zip_with_iterable(...)

See zip_with_iterable()

zip_with_list(...)

See zip_with_list()

class giving.gvn.ObservableProxy

Base class for Given which provides most of the methods.