Skip to main content

Work around mutable default arguments in function definitions

Project description

#########
staticargs
#########
**A clean way to work around mutable default arguments in python functions**

Get staticargs
=============

staticargs supports Python 2 and 3. Tests are run for 2.7 and 3.4

.. code-block:: shell

pip install staticargs

Run the tests
=============
You must install tox, then run:

.. code-block:: shell

git clone https://github.com/HurricaneLabs/staticargs.git
cd staticargs
tox

Example
--------

First view the problem we are going to solve:

.. code-block:: python

>>> def append_cat(cats=[]):
... cats.append("cat")
... return cats
...
>>> print(append_cat())
['cat']
>>> print(append_cat())
['cat', 'cat']
>>> print(append_cat())
['cat', 'cat', 'cat']
>>>

Well that's not good! Notice how even though we are appending "cat" only once, the number of items in the list returned gets bigger each time. Learn more about this problem and some other Python gotchas by watching this amazing presentation from PyCon 2015 (this specific problem is discussed at 8:04): https://youtu.be/sH4XF6pKKmk

staticargs solves this problem for you:

.. code-block:: python

>>> from staticargs import staticargs
>>> import random
>>>
>>> @staticargs
... def append_cat(cats=[]):
... #I love cats
... cats.append("cat")
... return cats
...
>>> print(append_cat())
['cat']
>>> print(append_cat())
['cat']
>>> print(append_cat())
['cat']
>>>
>>> @staticargs
... def store_dog(dogs={}):
... #Dogs are OK I guess
... dog_name = random.choice(["rufus", "muffins", "scooby"])
... dogs[dog_name] = "good boy"
... return dogs
...
>>> print(store_dog())
{'muffins': 'good boy'}
>>> print(store_dog())
{'scooby': 'good boy'}
>>> print(store_dog())
{'rufus': 'good boy'}
>>>

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

staticargs-1.0.0rc3.tar.gz (2.7 kB view details)

Uploaded Source

File details

Details for the file staticargs-1.0.0rc3.tar.gz.

File metadata

  • Download URL: staticargs-1.0.0rc3.tar.gz
  • Upload date:
  • Size: 2.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for staticargs-1.0.0rc3.tar.gz
Algorithm Hash digest
SHA256 1384c975653e0535035a0786e855cd35e06e94d51e88b70593feafce72f0db6b
MD5 42ff3334e603365fb80f119610b2fcf0
BLAKE2b-256 f814e1b5e62c38e7207a06ea9fafdfbc1907967ab1149f315502e52fed8d552f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page