box

class pythonic_fp.gadgets.box.Box

Bases: Generic

Box

Container holding at most one item of a given type.

Tip

Objects of the Box type

  • Are truthy if not empty.

  • Can be combined with other iterators before being filled.

  • Can be used like a promise.

  • Can be used in Python match statements.

  • Threadsafe

__init__(item: T) None
__init__() None

Initializer

Initialize Box with 0 or 1 items.

param item:

An optional initial item for the Box.

__bool__() bool

Bool

Truthy if not empty.

__iter__() Iterator

iter

yields:

Boxed item.

__len__() int

Length

  • 1 if Box contains an item

  • 0 if Box is empty

returns:

The number of items currently in the Box.

__eq__(other: object) bool

Equality comparison

Efficiently compare Box to another object.

param other:

The object to be compared.

returns:

True if other is another Box containing an object which compares as equal to the item contained in the Box, otherwise False.

__repr__() str

repr string

Construct string ‘Box()’ if empty, otherwise ‘Box(item_repr)’ where item_repr = repr(item) for the currently contained item.

returns:

A string to reproduce the current state of the Box.

__str__() str

user string

Construct string ‘Box()’ if empty, otherwise ‘Box(item_str)’ where item_str = str(item) for the currently contained item.

returns:

A user meaningful string to represent the current state of the Box.

get() T
get(alt: T) T

Get

Return the boxed item, if it exists, otherwise an alternate item, if given.

param alt:

An optional item of type T to return if the Box is empty.

returns:

Contents of Box or an alternate item, if given, when the Box is empty.

raises ValueError:

When the alt item is not provided but needed.

pop() T

Pop

Pop item from Box if not empty.

returns:

The item contained in the Box.

raises ValueError:

If Box is empty.

push(item: T) None

Push

Push an item into Box if empty.

param item:

Item to push into the empty Box.

raises ValueError:

If Box is not empty.

put(item: T) None

Put

Put an item in the Box. Discard any previous contents.

exchange(new_item: T) T

Exchange

Exchange an item with what is in the Box.

param new_item:

New item to exchange for current item.

returns:

Original contents of the Box.

raises ValueError:

If Box is empty.

map(f: Callable[[T], U]) Box

Map

Map function f over contents. We need to return a new instance since the type of Box can change.

param f:

Mapping function.

returns:

New instance.

bind(f: Callable[[T], Box]) Box

Bind

Flatmap Box with function f.

param f:

Binding function.

returns:

New instance.