Asked • 05/06/19

Why are default arguments evaluated at definition time in Python?

I had a very difficult time with understanding the root cause of a problem in an algorithm. Then, by simplifying the functions step by step I found out that evaluation of default arguments in Python doesn't behave as I expected. The code is as follows: class Node(object): def __init__(self, children = []): self.children = children The problem is that every instance of Node class shares the same `children` attribute, if the attribute is not given explicitly, such as: >>> n0 = Node() >>> n1 = Node() >>> id(n1.children) Out[0]: 25000176 >>> id(n0.children) Out[0]: 25000176 I don't understand the logic of this design decision? Why did Python designers decide that default arguments are to be evaluated at definition time? This seems very counter-intuitive to me.

Steven F.

In python, functions are objects. When you define the function, an object (function object) actually gets instantiated and stored, just like any other object. So when you call the function, you are making use of this object. If you call it twice, you're using the same function object, which has the same default arguments.


1 Expert Answer


Hayward B. answered • 07/31/20

New to Wyzant

python developer, software enginneer

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.


Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.