Skip to main content

Utility for initialization ensuring functions are called only once

Project description

Once

This library provides functionality to ensure a function is called exactly once in Python, heavily inspired by std::call_once.

During initialization, we often want to ensure code is run exactly once. But thinking about all the different ways this constraint can be violated can be time-consuming and complex. We don't want to have to reason about what other callers are doing and from which thread.

Introducing a simple solution - the once.once decorator! Simply decorate a function with this decorator, and this library will handle all the edge cases to ensure it is called exactly once! The first call will invoke the function, and all subsequent calls will return the same result. Enough talking, let's cut to an example:

import once

@once.once
def my_expensive_object():
    load_expensive_resource()
    load_more_expensive_resources()
    return ObjectSingletonUsingLotsOfMemory()

def caller_one():
    my_expensive_object().use_it()

def caller_two_from_a_separate_thread():
    my_expensive_object().use_it()

def optional_init_function_to_prewarm():
    my_expensive_object()

This module is extremely simple, with no external dependencies, and heavily tested for races.

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

once_py-0.0.3-py3-none-any.whl (8.6 kB view details)

Uploaded Python 3

File details

Details for the file once_py-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: once_py-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 8.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.6

File hashes

Hashes for once_py-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 65b01bcf37f2e8cc40c00a324b25dffaa285120090f5ea758e635ec323829909
MD5 ac22fd1600e1e6fe8189ee11a5ded3e1
BLAKE2b-256 85f0a8af12e2ec224e3dcd77417f406715ec2a85d0c564ca21e2959c8eb8d7ca

See more details on using hashes here.

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