Python Warts

misfeatures and other problems
PERL| PHP| PYTHON| RUBY
Answers: (all questions)
(question)
Question:
#!/usr/bin/python

def add_evil(data=[]):
	data.append(666)
	return data

print add_evil()
print add_evil(["hi there"])
print add_evil()
print add_evil()
Answer:
The output is:
[666]
['hi there', 666]
[666, 666]
[666, 666, 666]
Python has a bizarre way of handling default parameters. It binds the default value once, when the function is defined, instead of doing it each time the function is called. So, if a default value is mutable, its value may be different on successive calls.

Using mutable default values is not recommended.
PERL| PHP| PYTHON| RUBY
Last modified: March 30, 2006 @ 7:04 MST
Copyright (C) 1996-2024 Selene ToyKeeper