Skip to main content

Helper decorator to lock default mutable values

Project description


PyPI License Copy and Paste

This decorator is small and only relies on the standard library, so can just be copied into a project.

Python has a weird behaviour around default values for functions. If you use an empty list as a default argument, things added to the list during the function can hang around for next time the function is called. A common pattern of dealing with this is the following:

def func(foo = None):
    if foo is None:
        foo = []

But this looks rubbish! And gets worse when you add typing:

def func(foo: list | None = None):
    if foo is None:
        foo = []

You don't need that workaround for any other of default value. Why does the list parameter have to pretend it can be None, when that's not the intention at all?

The lockmutabledefaults decorator fixes this by introducing what should be the default approach, and default values that are lists, dictionaries or sets are isolated in each re-run.

def func(foo: list = []):


You can install from pip: python -m pip install lock-defaults

Or you can copy the function directly into your projects.

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

lock-defaults-0.1.4.tar.gz (3.7 kB view hashes)

Uploaded Source

Built Distribution

lock_defaults-0.1.4-py3-none-any.whl (6.0 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