Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/aloiziomacedo/stabledefaults
Allows for mutable defaults comfortably and intuitively.
https://github.com/aloiziomacedo/stabledefaults
decorators decorators-python functions python
Last synced: 2 days ago
JSON representation
Allows for mutable defaults comfortably and intuitively.
- Host: GitHub
- URL: https://github.com/aloiziomacedo/stabledefaults
- Owner: AloizioMacedo
- License: mit
- Created: 2023-01-19T01:26:38.000Z (almost 2 years ago)
- Default Branch: master
- Last Pushed: 2023-01-20T02:15:43.000Z (almost 2 years ago)
- Last Synced: 2024-10-07T09:07:22.685Z (about 1 month ago)
- Topics: decorators, decorators-python, functions, python
- Language: Python
- Homepage: https://stabledefaults.readthedocs.io
- Size: 38.1 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 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:
```python
def f(x=[]):
x.append(2)
return x
``````python
>>> a = f()
>>> a
[2]
>>> f()
>>> a
[2, 2]
```Nevertheless, this is unintuitive. Not only that, but dealing with this requires things such as
```python
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
```python
@stabledefaults()
def f(x=[]):
x.append(2)
return x
```
```python
>>> a = f()
>>> a
[2]
>>> f()
>>> a
[2]
```