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.

Parameters:

item – An optional initial item for the Box.

__bool__() bool

Bool

Truthy if not empty.

__iter__() Iterator

Iterability

Iterates 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.

Parameters:

other – The object to be compared.

Returns:

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

__repr__() str

Representation 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.

get() T
get(alt: T) T

Get

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

Parameters:

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.

Parameters:

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.

Parameters:

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.

Parameters:

f – Mapping function.

Returns:

New instance.

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

Bind

Flatmap Box with function f.

Parameters:

f – Binding function.

Returns:

New instance.