box

Class for a stateful container that can hold at most one item.

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

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.

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

Flatmap Box with function f.

Parameters:

f – binding function

Returns:

a new instance

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.

get() T
get(alt: T) T

Return the contained item if it exists, otherwise an alternate item.

Parameters:

alt – an “optional” item of type T to return if Box is empty

Returns:

contents of Box, or an alternate item if given and Box empty

Raises:

ValueError – when an alt item is not provided but needed

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

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.