Default parameter considerations when Python defines a function

Source: Internet
Author: User

If the default argument is not passed when a function is called, the default parameter within the function is a reference to the function's default parameter property, __defaults__.

Such as

def func (arg1=[]):    arg1.append (2)

If there are no arguments when calling Func, the above arg1 is a reference to func.__defaults__[0]

Default parameters are not passed, the following conditions occur

Because Func.__defaults__[0] is a mutable type, each call to FUNC,ARG1 will operate on Func.__defaults__[0] (Func.__defaults__[0].append (2),

This can lead to logic errors in some cases, such as

def func (arg1=[]):    if(arg1==[]):        print'arg1 is Empty'        arg1.append (1)    Else:          Print'arg1 is not empty'        print  arg1func () # Arg1 is empty
Func () #arg1 is not empty  [1]

The second time the Func is called, the parameter arg1 is not passed, but the function has been modified internally since the first call __defaults__

Why is this? Why does the second call not reset Arg1 to []?

Because

The default parameters for Python are determined only when the function is defined, not each time it is called, so once the default parameters are modified in the function, the subsequent calls will take effect

Because of this feature, when defining a function, if the default parameter uses a Mutable object type, as in the example above, it is likely to cause a logical error.

So, if not specifically required, the Func.__defaults__ property referenced by the default parameter is not allowed to be modified inside the function, so how can an object not be modified? That is to cancel its reference to __defaults__ before manipulating arg1

The above example changes a bit

def func (arg1=[]):    if(arg1==[]):        print'arg1 is Empty'        arg1=[]        arg1.append (1)    Else :         Print ' arg1 is not empty '        Print arg1

In the example above, when the user does not pass the default parameter arg1, the function internally assigns a value to the ARG1 variable, letting arg1 refer to the object we want to use [], so arg1 will not modify func.__defaults__

If the default parameter is a value, you can do so

def func (arg1=[1,2,3]):    if(arg1==[1,2,3]):        print' is [+ + ] '         arg1# Here's the point, cancel the Arg1 reference to the __defaults__ property and prevent arg1 modification __defaults__        Arg1.append (1)    Else:        print'not[+]  '        print arg1

The above is too verbose, the following example imitates the official Python example, using immutable types (such as none) as the default parameters, logic concise, recommended to use

def #默认参数to none is defined, but the function logic is further re-assigned to the default value you want to use
if is None: = [to.append] (element )return to

Summarize:

To prevent default parameters from modifying the __defaults__ of a function, you need:

1. When defining default parameters, it is best to use immutable types.

2. If you must use a mutable type for the default parameter, re-assign the default parameter to a variable type's value inside the function.

Default parameter considerations when Python defines a function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.