You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

constify

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

constify

Makes functions parameters immutable

0.1.0
pipPyPI
Maintainers
1

Python License MIT Coverage Status Unit Tests Tox Ruff Mypy

Constify

The constify library provides the freezeparams decorator to make mutable default values and arguments passed to functions immutable.

Why use the freezeparams decorator ?

[1] The default value of a parameter is evaluated only once, which can lead to unexpected behavior if the value is a mutable object, such as a list or a dictionary. For example, the following function accumulates arguments across calls:

Example

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))  # [1]
print(f(2))  # [1, 2]
print(f(3))  # [1, 2, 3]

To prevent this default value from being shared, the function can be rewritten as follows:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

This solution is effective, but with multiple mutable default values, it requires many checks. The freezeparams decorator simplifies the use of mutable objects as default values and arguments.

Installation

pip install constify

Usage

from constify import freezeparams

@freezeparams
def f(a, L=[]):
    L.append(a)
    return L

# Default value (list) remains unchanged
print("f(1) =>", f(1))  # [1]
print("f(2) =>", f(2))  # [2]
print("f(3) =>", f(3))  # [3]

print("-" * 25) # just a separator

# Passed list remains intact
x = [1, 2]
print("x =", x)  # [1, 2]
print(f"f(3, {x}) =>", f(3, x))  # [1, 2, 3]
print(f"f(4, {x}) =>", f(4, x))  # [1, 2, 4]
print("x =", x)  # [1, 2]

You can comment out the decorator and run the code again to see the difference.

Simple and effective!

Sources

[1] https://docs.python.org/3.13/tutorial/controlflow.html#default-argument-values

Keywords

mutable

FAQs

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts