10

考虑我kwargs在方法中更改 dict 的情况:

def print_arg(**kwargs):
    print kwargs.pop('key')

pop_arg如果我用这样的字典调用该方法:

mydict = {'key':'value'}
print_arg(**mydict)

mydict被这个电话改变吗?

我也对允许mydict更改或不更改的底层方法调用机制的更详细解释感兴趣。

4

3 回答 3

16

不,mydict不会改变。kwargs 被解压成一本新字典。

考虑以下情况:

def print_arg(key=1, **kwargs):
    print(key)
    print(kwargs)

print_arg(**{'key':2,'foo':3,'bar':4})

在这种情况下,很明显 kwargs 与您传入的字典不同,因为当它被解包时,它丢失了'key'密钥。

于 2013-04-16T14:07:07.640 回答
8

@mgilson 的回答是正确的。但是你也应该注意浅拷贝。

def print_arg(**kwargs):
    print kwargs.pop('key')
    kwargs['list'].pop()  # will affect the original
    kwargs['dict'].pop('a') #will affect the original

mydict = {'key':'value', 'list':[2,3,4,5] ,'dict': { 'a':1,'b':2 }}
print_arg(**mydict)
print (mydict)  # Output : {'dict': {'b': 2}, 'list': [2, 3, 4], 'key': 'value'}

http://codepad.org/diz38tWF

于 2013-04-16T14:13:19.350 回答
6

Let's see:

import dis
dis.dis(lambda: print_arg(**{'key': 'value'}))

 

  6           0 LOAD_GLOBAL              0 (print_arg)
              3 BUILD_MAP                1
              6 LOAD_CONST               1 ('value')
              9 LOAD_CONST               2 ('key')
             12 STORE_MAP           
             13 CALL_FUNCTION_KW         0
             16 RETURN_VALUE        

 

Let's find what CALL_FUNCTION_KW does (ceval.c):

    case CALL_FUNCTION_VAR:
    case CALL_FUNCTION_KW:
    case CALL_FUNCTION_VAR_KW:
    {

        // ... 

        x = ext_do_call(func, &sp, flags, na, nk);

        // ...

 

static PyObject *
ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
{
    int nstar = 0;
    PyObject *callargs = NULL;
    PyObject *stararg = NULL;
    PyObject *kwdict = NULL;
    PyObject *result = NULL;

    if (flags & CALL_FLAG_KW) {                     // if ** is involved
        kwdict = EXT_POP(*pp_stack);        // get the dict passed with **      
        if (!PyDict_Check(kwdict)) {
            PyObject *d; 
            d = PyDict_New();                       // make a NEW dict
            if (d == NULL)
                goto ext_call_fail;
            if (PyDict_Update(d, kwdict) != 0) {    // update it with old
                // .. fail ..
                goto ext_call_fail;
            }
            Py_DECREF(kwdict);   
            kwdict = d;              // kwdict is now the new dict
        }
    }

    ....  
    result = PyObject_Call(func, callargs, kwdict);  // call with new dict
于 2013-04-16T14:16:36.633 回答