box

class pythonic_fp.gadgets.box.Box(item: T)
class pythonic_fp.gadgets.box.Box

Container holding at most one item of a given type.

Note

  • Box(item: T): contains at one item of type T

  • Box[T](): creates empty container

Where type T is some definite type, which could be None or even Never.

Tip

Box objects can be used in Python match statements.

Parameters:

item – An optional initial contained item for the Box.

__init__(item: T) None
__init__() None
Parameters:

item – An optional initial contained item for the Box.

__repr__() str

Return repr(self).

__eq__(other: object) bool

Efficiently compare to another object.

Parameters:

other – The object to be compared with,

Returns:

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

get() T
get(alt: T) T

Return the contained 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 the contained item if Box is not empty.

Returns:

The item contained in the Box.

Raises:

ValueError – If Box is empty.

push(item: T) None

Push an item into an empty Box.

Parameters:

item – Item to push into the empty Box.

Raises:

ValueError – If Box is not empty.

put(item: T) None

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

exchange(new_item: T) T

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 function f over contents. We need to return a new instance since the type of Box can change.

Parameters:

f – Mapping function.

Returns:

A new instance.

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

Flatmap Box with function f.

Parameters:

f – Binding function.

Returns:

A new instance.