Skip to main content

Little python package implementing optional chaining

Project description

Safebag

Stable Version

Safebag is a little python package implementing optional chaining.

Installation

pip install safebag

Usage

chain [source]

Optional chain constructor

Optional chain constructed from any object.

Chain is used for building sequence of null-safe attribute calls.

from __future__ import annotations

import dataclasses as dt
import typing


@dt.dataclass
class Node:
    data: int
    node: typing.Optional[Node]


nodes = Node(data=1, node=Node(data=2, node=None))

from safebag import chain

third_node_proxy = chain(nodes).node.node.node
print(third_node_proxy)  # ChainProxy(data_object=None, bool_hook=False)

get_value [source]

Final value getter for optional chain.

Optional chain constructed from any object. Chain is used for building sequence of null-safe attribute calls.

from __future__ import annotations

import dataclasses as dt
import typing


@dt.dataclass
class Node:
    data: int
    node: typing.Optional[Node]


nodes = Node(data=1, node=Node(data=2, node=None))

from safebag import chain, get_value

third_node_proxy = chain(nodes).node.node.node
value = get_value(third_node_proxy)
assert value is None

next_node = chain(nodes).node
value = get_value(next_node)  # Node(data=2, node=None)

Useful in combination with walrus operator:

if next_node := chain(nodes).node.node:
    print(get_value(next_node))

if next_node := chain(nodes).node:
    print(get_value(next_node))  # Node(data=2, node=None)

ChainProxy [source]

ChainProxy container:

  • stores data_object
  • proxying data_object attribute value into new ChainProxy instance when attribute is invoked. If attribute does not exist or attribute value is None. ChainProxy instance data_object will be None and bool_hook will be False.
  • ChainProxy instance always returning when attribute is invoked.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

safebag-0.1.7.tar.gz (3.7 kB view hashes)

Uploaded Source

Built Distribution

safebag-0.1.7-py3-none-any.whl (5.2 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page