0

I got this question from the answer of this post.

consider this code

def test(a,dict={}):
     b=5
     dict[a]=1
     print dict
     print locals()

test(1)

test(2)

The output is:

{1: 1}
{'a': 1, 'b': 5, 'dict': {1: 1}}
{1: 1, 2: 1}
{'a': 2, 'b': 5, 'dict': {1: 1, 2: 1}}

As I can infer, there is a "global" reference to the dict.

what is passed as default parameter to the function is persistent somewhere in the namespace.

It is shared across when the function is called again. but how do I know what the current dict holds. I can have a dict outside of the function and pass that dict to the function to know what the dict holds.

But my question is where the default parameter of dict is present (in the namespace) and how to access it. when is this dict created? when the function is called first time or when the def statement is executed?

btw, printing the locals() shows that dict is local to function

Thanks

3
  • Aside: please don't name your variables after the type. The variable name makes the type name inaccessible, leading to hard-to-find bugs. Commented Nov 13, 2013 at 20:54
  • @Robᵩ: Thanks for the note, I will follow this Commented Nov 13, 2013 at 20:57
  • Hmm, we may have been wrong to close as a dup. From the OP's comment on the answer, the standard Q&A is certainly something that will help the OP understand what's going on, but the question about "where the default parameter of dict is present (in the namespace) and how to access it" is separate. Commented Nov 13, 2013 at 21:03

1 Answer 1

1

Look at test.func_defaults or perhaps test.__defaults__. I think you'll find what you seek there.

Reference: http://effbot.org/zone/default-values.htm

Sign up to request clarification or add additional context in comments.

2 Comments

that helped, when is this dict created. is it when the function is called or when the def statement is executed?
The default arg is created once, when the def is executed. The function call merely binds the argument name to the already-existing default argument object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.