gadgets.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(value: D)

Container holding at most one item of a given type

  • where Box(item) contains at most one item of type D

    • Box[T]() creates empty container

      • where T is some definite type

      • which could be None or even Never

  • Box objects can be used in Python match statements

Initialize Box with an “optional” initial value.

Parameters:

value – an “optional” initial value for Box.

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

Flatmap Box with function f.

Parameters:

f – binding function

Returns:

a new instance

exchange(new_item: D) D | Never

Exchange an item with what is in the Box.

Raises:

ValueError – if Box is empty

get() D | Never
get(alt: D) D

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

Parameters:

alt – an “optional” value to return if Box is empty

Returns:

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

Raises:

ValueError – when an alt value is not provided but needed

map(f: Callable[[D], T]) 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() D | Never

Pop the value if Box is not empty.

Returns:

value contained in Box

Raises:

ValueError – if Box is empty

push(item: D) None | Never

Push an item in an empty Box.

Raises:

ValueError – if Box is not empty

put(item: D) None

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