Skip to main content

Allows for mutable defaults comfortably and intuitively.

Project description

Introduction

stabledefaults is a small package containing a decorator to allow for the expected behavior of lists, dicts and other mutable arguments in default arguments.

Explanation

In Python, functions (as anything else) are objects, and the default arguments are stored as attributes that are initialized in definition.

Once this is known and the person understands that variables are references in Python, then it is relatively straightforward to understand the following behavior:

def f(x=[]):
    x.append(2)
    return x
>>> a = f()
>>> a
[2]
>>> f()
>>> a
[2, 2]

Nevertheless, this is unintuitive. Not only that, but dealing with this requires things such as

def f(x = None):
    if x is None:
        x = []

    x.append(2)
    return x

which forces types such as list | None where just list should suffice, and also forces code inside the function itself.

This package solves this issue with a decorator. For instance, the example above would become

@stabledefaults()
def f(x=[]):
    x.append(2)
    return x
>>> a = f()
>>> a
[2]
>>> f()
>>> a
[2]

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

stabledefaults-0.1.4.tar.gz (3.0 kB view details)

Uploaded Source

Built Distribution

stabledefaults-0.1.4-py3-none-any.whl (3.4 kB view details)

Uploaded Python 3

File details

Details for the file stabledefaults-0.1.4.tar.gz.

File metadata

  • Download URL: stabledefaults-0.1.4.tar.gz
  • Upload date:
  • Size: 3.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.16

File hashes

Hashes for stabledefaults-0.1.4.tar.gz
Algorithm Hash digest
SHA256 2518225f2103ea801d0148fba07bc414c79f4552f38a718b0cc0a3c224e14432
MD5 b7452fc2a4f905d3a7a3587902b81585
BLAKE2b-256 757a6ac076b8136478aaf5c85909706e614f1d0c0701b0f9aeb8b64a50715757

See more details on using hashes here.

File details

Details for the file stabledefaults-0.1.4-py3-none-any.whl.

File metadata

File hashes

Hashes for stabledefaults-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 a800d58de18645a8036d2b4f673abc4549105d335abe414faa498dcdb6104bbe
MD5 8c1b2b730889f8cfb9710ad29cb0e63f
BLAKE2b-256 6381111a92d53483e76fad38b00d69ffc291cd9b41e59cfe92f6dd00991d621e

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