Does dict.update affect the argspec function?

import inspect class Test: def test(self, p, d={}): d.update(p) return d print inspect.getargspec(getattr(Test, 'test'))[3] print Test().test({'1':True}) print inspect.getargspec(getattr(Test, 'test'))[3] 

I would expect the argspec for Test.test to not change, but due to dict.update this will happen. Why?

+4
source share
2 answers

Because dicts are mutable objects. When you call d.update(p) , you are actually mutating the default instance of dict. This is a common catch; in particular, you should never use a mutable object as the default value in an argument list.

The best way to do this is:

 class Test: def test(self, p, d = None): if d is None: d = {} d.update(p) return d 
+5
source

The default argument in Python is any object that was specified when defining a function, even if you set a mutable object. This question should explain what this means and why Python is an SO question. The least surprising thing in python is: a mutable default argument .

Basically, the same object is used by default every time a function is called, and not every time a new copy is created. For instance:

 >>> def f(xs=[]): ... xs.append(5) ... print xs ... >>> f() [5] >>> f() [5, 5] 

The easiest way is to create the actual default argument None , and then just check for None and specify the default value in the function, for example:

 >>> def f(xs=None): ... if xs is None: ... xs = [] ... xs.append(5) ... print xs ... >>> f() [5] >>> f() [5] 
+2
source

Source: https://habr.com/ru/post/1308247/


All Articles