I was wondering if the ‘a=a’, and ‘b=b’ can lead to problems/unexpected behaviour? code works fine in the example.
def add_func(a=2,b=3):
return a+b
a=4
b=5
answer = add_func(a=a, b=b)
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Not that I know of, although I’d love to be proved wrong.
The formal language reference defines the lexical structure of a function call. The important bit is that it defines a “keyword_item” as
identifier "=" expression. Also, here’s what it says about how the arguments to the call are interpreted:This lists a few possible scenarios.
In the simple case, like you mentioned, where there are two formal arguments (
aandb), and if you specify the function call using keyword parameters likeadd_func(a=a, b=b), here’s what happens:a=part) is compared with all of the formal parameters names of the function (the names that were given the parameters when the function was defined, in our case,aandb).4!) is used to fill the corresponding slot.So, Python treats the “identifier” in a keyword argument completely differently. This is only true for keyword arguments, though; obviously, if you tried something like
add_func(b, a), even though your parameters themselves are calledbanda, this would not be mapped to the formal parameters in the function; your parameters would be backwards. However,add_func(b=b, a=a)works fine; the positions don’t matter as long as they are keyword arguments.