Skip to main content

lazy-string

Python library for defining strings with delayed evaluation.

Version of PyPI package Supported versions of Python MIT license

The package provides a LazyString class. Its constructor accepts a callable (say, a function) which will be called when string’s value is needed. The constructor also allows to specify positional and keyword arguments for that callable:

def __init__(self, func: Callable[..., str], *args: Tuple, **kwargs: Mapping) -> None:
  ...

The value is re-evaluated on every access.

Installation

Available as a PyPI package:

pip install lazy-string

Usage

Using with a function having no parameters:

from lazy_string import LazyString

def make_foo() -> str:
  return "foo"

s = LazyString(make_foo)

The value is evaluated on demand:

>>> s + " bar"
'foo bar'

>>> str(s)
'foo'

Representation explicitly tells it’s a LazyString:

>>> s
LazyString('foo')

It’s safe to pass standard strings, as they will be returned as-is:

>>> LazyString("foo bar")
'foo bar'

Supports methods of standard strings:

>>> s.upper()
'FOO'

>>> "f" in s
True

>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
 '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
 '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
 '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
 '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Supplying parameters for the callable:

def make_foo(arg1, arg2):
  return f"foo {arg1} {arg2}"

s = LazyString(make_foo, 123, arg2=456)
>>> str(s)
'foo 123 456'

Implementation Details

LazyString is inherited from collections.UserString.

>>> LazyString.__mro__
(<class 'lazy_string.LazyString'>, <class 'collections.UserString'>,
 <class 'collections.abc.Sequence'>, <class 'collections.abc.Reversible'>,
 <class 'collections.abc.Collection'>, <class 'collections.abc.Sized'>,
 <class 'collections.abc.Iterable'>, <class 'collections.abc.Container'>,
 <class 'object'>)

Serialization

Pickling

Supported out of the box:

>>> import pickle
>>> s == pickle.loads(pickle.dumps(s))
True

To JSON

Supported with any encoder able to encode collections.UserString:

import json
import collections

class JSONEncoder(json.JSONEncoder):

  def default(self, o):
    if isinstance(o, collections.UserString):
      return str(o)
    return super().default(o)
>>> data = {'s': s}
>>> json.dumps(data, cls=JSONEncoder)
'{"s": "foo"}'

Metadata

Release files for lazy-string 1.0.0

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

Source distribution (sdist)

Source distribution for lazy-string 1.0.0
File Size Uploaded Provenance Actions
lazy-string-1.0.0.zip 10.1 kB Without provenance Details for lazy-string-1.0.0.zip

Release files / lazy-string-1.0.0.zip

Download URL lazy-string-1.0.0.zip
Size 10.1 kB
Tags Source
SHA-256 checksum
How to use checksums
dfca872cbcf5f31736702009001616e22189d34b8ba12819b55e2ed6e91726f1
BLAKE2b-256 checksum
How to use checksums
9dbf4ed43c60a277344ea12f9f8194d45fcd663bc4b8f2495295f5e60bc3429f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.8.6

Security for lazy-string 1.0.0

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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

1 release file No provenance

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