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

Community
  • 1
  • 1
brain storm
  • 30,124
  • 69
  • 225
  • 393
  • *Aside*: please don't name your variables after the type. The variable name makes the type name inaccessible, leading to hard-to-find bugs. – Robᵩ Nov 13 '13 at 20:54
  • @Robᵩ: Thanks for the note, I will follow this – brain storm Nov 13 '13 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. – DSM Nov 13 '13 at 21:03

1 Answers1

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

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • that helped, when is this `dict` created. is it when the function is called or when the def statement is executed? – brain storm Nov 13 '13 at 21:01
  • 1
    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. – Robᵩ Nov 13 '13 at 21:06