Skip to main content

Plyr: computing on nested containers

plyr [/plaɪ'ə/], derived from applier, is a python C-extension, that implements a map-like logic, which computes a specified function on the lower-most non-container data of arbitrarily nested built-in python containers, i.e. dicts, lists, tuples. It automatically unpacks nested containers in order to call the same function on their underlying non-container objects and then reassembles the structures. See the docstring of plyr.apply for details.

plyr happens to coincide with a similarly named library for R statistical computations language, which streamlines dataframe and vector/matrix transformations.

Setup

The package can be installed from pip:

pip install python-plyr

The development environment could be initialized with the following commands:

# create a dedicated env
conda create -n plyr "python>=3.7" pip pytest twine \
  && conda activate plyr \
  && pip install build

# build and install
pip install -e . -vv

the Essential Example

Below we provide an example, which, we hope, illustrates the cases plyr might be useful in.

import plyr
from collections import namedtuple

nt = namedtuple("nt", "u,v")

# add the leaf data in a pair of nested objects
plyr.apply(
    lambda u, v: u + v,
    [{"a": (1, 2, 3), "z": 3.1415}, nt([1, "u"], "abc")],
    [{"a": (4, 6, 8), "z": 2.7128}, nt([4, "v"], "xyz")],
    # _star=True,  # (default) call fn(d1, d2, **kwargs)
)
# output: [{'a': (5, 8, 11), 'z': 5.8543}, nt(u=[5, 'uv'], v='abcxyz')]

# join strings in a pair of tuples
plyr.apply(
    " -->> ".join,
    ("abc", "uvw", "xyz"),
    ("123", "456", "789"),
    _star=False,  # call fn((d1, d2,), **kwargs)
)
# output: ('abc -->> 123', 'uvw -->> 456', 'xyz -->> 789')

By default .apply performs safety checks to ensure identical structure if multiple nested objects are given. If the arguments have identical structure by design, then these integrity checks may be turned off by specifying _safe=False. Please refer to the docs of plyr.apply.

plyr.ragged is a special version of .apply which implements leaf broadcasting semantics. When processing multiple nested objects it allows one structure to subsume the other structures: any intermediate leaf data is broadcasted deeper into the hierarchy of the other nested structures. Please refer to ./doc/mapping_structures.ipynb for details.

Serializing and deserializing

Serialization and deserialization of nested objects can be done by .flatten and .unflatten. The following snippet shows how to represent a given nested object as a flat list and then undo the process.

import plyr

o = [1, (2, 3), {"a": (4, 5), "z": {"a": 6}}, 7]

flat, skel = plyr.flatten(o)
assert o == plyr.unflatten(flat, skel)

flat
# output: ([1, 2, 3, 4, 5, 6, 7]

This next example demonstrates how to unpack a stream of data into nested objects.

import plyr

stream, _ = iter(range(13)), None

struct = ({"foo": _, "bar": [_, _]}, _)

objects = [plyr.unflatten(stream, struct) for _ in range(3)]

The following example illustrates how to compute the a functon over a nested object and invert the structure (see .iapply):

import plyr


def func(x, y):
    return {"z": x * y}, -y


# `inverted` shall nests the original structure of `o` _under_ func's
#  return-value structure
flat, struct = plyr.flatapply(func, (2, {"a": 1},), (4, {"a": 3},))
inverted = plyr.apply(plyr.unflatten, *flat, _star=False, struct=struct)

inverted
# output: ({'z': (8, {'a': 3})}, (-4, {'a': -3}))

Here's how one might broadcast a value across the structure of a specified nested object.

import plyr

struct = {"foo": {"bar": 1}, "baz": (2, 3)}

const = "abc"
broadcast = plyr.apply(lambda x: const, struct)

broadcast
# output: {'foo': {'bar': 'abc'}, 'baz': ('abc', 'abc')}

Other Examples

Below we perform something fancy with numpy. Specifically, we stack outputs from some experiments (dicts of arrays), to get the standard deviation between the results.

import plyr
import numpy as np


# some computations
def experiment(j):
    return dict(
        a=float(np.random.normal()),
        u=np.random.normal(size=(5, 2)) * 0.1,
        z=np.random.normal(size=(2, 5)) * 10,
    )


# run 10 replications of an experiment
results = [experiment(j) for j in range(10)]

# stack and analyze the results (np.stack needs an iterable argument)
res = plyr.apply(np.stack, *results, axis=0, _star=False)

# get the shapes
shapes = plyr.apply(lambda x: x.shape, res)

# compute the std along the replication axis
plyr.apply(np.std, res, axis=0)

You may notice that .apply is very unsophisticated: it applies the specified function to the leaf data regardless of its type, and every dict, list, or tuple is always treated as a nested container.

Metadata

Release files for python-plyr 0.8.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for python-plyr 0.8.1
File Size Uploaded Provenance Actions
python-plyr-0.8.1.tar.gz 19.8 kB Without provenance Details for python-plyr-0.8.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for python-plyr 0.8.1
File Interpreter ABI Platform Actions
python_plyr-0.8.1-cp310-cp310-macosx_10_9_x86_64.whl CPython 3.10 CPython 3.10 macOS 10.9+ x86-64 Details for python_plyr-0.8.1-cp310-cp310-macosx_10_9_x86_64.whl

Total release size: 43.6 kB

Release files / python-plyr-0.8.1.tar.gz

Download URL python-plyr-0.8.1.tar.gz
Size 19.8 kB
Tags Source
SHA-256 checksum
How to use checksums
f3154b34195ccc78d7e18441d809c2af042585c2cdd9664b972258fe7e61b42c
BLAKE2b-256 checksum
How to use checksums
eaf8802fdc568f1273b4f3cb7844f592b6ce8f038f4d7654fab2dde098eb5f88
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.7.1 importlib_metadata/4.11.3 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.64.0 CPython/3.10.4

Release files / python_plyr-0.8.1-cp310-cp310-macosx_10_9_x86_64.whl

Download URL python_plyr-0.8.1-cp310-cp310-macosx_10_9_x86_64.whl
Size 23.8 kB
Tags CPython 3.10 macOS 10.9+ x86-64
SHA-256 checksum
How to use checksums
ef9a2ec638864563c52a85782cf687b728c215e06822f09abf6473c57525dae2
BLAKE2b-256 checksum
How to use checksums
5d381db91c0c378df41056db1c18547c4348fe11d29addebb9f2933bc2356cb0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.7.1 importlib_metadata/4.11.3 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.64.0 CPython/3.10.4

Security for python-plyr 0.8.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page