Object.assign equivalent in python

Viewed 247

Is there an equivalent for Javascript's Object.assign(targetDict, srcDict) in python, which takes all the items from one dictionary into another, replacing as we go? (Cleaner than a for-in loop, anyhow)

------ Context ---------

I use Object.assign in javascript to expand out settings-dictionary parameters in large functions, e.g.:

function someFunctionWithLotsOfArguments(namedArg1, namedArg2, namedArg3, namedArg4){}
// turns into
function someFunctionWithLotsOfArguments(argDictionary){
    namedArg1 = argDictionary["namedArg1"]; // etc
}

The first form allows for default arguments while the second one does not, so I then use:

function someFunctionWithLotsOfArguments(namedArg1="default1", namedArg2="default2", namedArg3="default3", namedArg4="default4"){}
// turns into
function someFunctionWithLotsOfArguments(argDictionary){
    defaultArgs = {
        namedArg1: "default1",
        namedArg2: "default2",
        namedArg3: "default3",
        namedArg4: "default4"
    }
    Object.assign(defaultArgs, argDictionary);
    argDictionary = defaultArgs;
    namedArg1 = argDictionary["namedArg1"]; // etc
}

I know, I know, this is a bit of an antipattern, and I should try and group my named arguments into structs to reduce my function parameter count, and if I have a large configurable function with many binary switches I should strip out the common functionality into smaller functions, etc. But if I did need a function like this, is there one available?

1 Answers

Python has a dict1.update(dict2) method which will do exactly that. :)

Related