Skip to content

Commit fd9f0db

Browse files
committed
First gotcha.
1 parent a31384a commit fd9f0db

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

docs/contents.rst.inc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ This part of the guide focuses on best practices for writing Python code.
3131
writing/style
3232
writing/documentation
3333
writing/tests
34+
writing/gotchas
3435
writing/license
3536

3637

docs/writing/gotchas.rst

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
Common Gotchas
2+
==============
3+
4+
For the most part, Python aims to be a clean and consistent language that
5+
avoid surprises, but there are a few cases where newcomers to the language
6+
often get tripped up.
7+
8+
Some of these are intentional but surprising. Some could arguably be considered
9+
language warts. In general though, what follows is a collection of potentially
10+
tricky behavior that might seem strange at first glance, but is generally
11+
sensible despite surprise after learning of its existence.
12+
13+
14+
Mutable Default Arguments
15+
-------------------------
16+
17+
Seemingly the *most* common surprise new Python programmers encounter is
18+
Python's treatment of mutable default arguments in function definitions.
19+
20+
**What You Wrote**
21+
22+
.. code-block:: python
23+
24+
def append_to(element, to=[]):
25+
to.append(element)
26+
return to
27+
28+
**What You Might Have Expected to Happen**
29+
30+
A new list is created each time the function is called if a second argument
31+
isn't provided.
32+
33+
**What Does Happen**
34+
35+
A new list is created *once* when the function is defined, and the same list is
36+
used in each successive call.
37+
38+
Python's default arguments are evaluated *once* when the function is defined,
39+
not each time the function is called (like it is in say, Ruby). This means that
40+
if you use a mutable default argument and mutate it, you *will* and have
41+
mutated that object for all future calls to the function as well.
42+
43+
**What You Should Do Instead**
44+
45+
Create a new object each time the function is called, by using a default arg to
46+
signal that no argument was provided (``None`` is often a good choice).
47+
48+
.. code-block:: python
49+
50+
def append_to(element, to=None):
51+
if to is None:
52+
to = []
53+
to.append(element)
54+
return to
55+
56+
57+
**When the Gotcha Isn't a Gotcha**
58+
59+
Sometimes you specifically can "exploit" (read: use as intended) this behavior
60+
to maintain state between calls of a function. This is often done when writing
61+
a caching function.

0 commit comments

Comments
 (0)