[Python] Problem with Default Arguments

Source: Internet
Author: User

Default arguments is a helpful feature and there is one situation where they can surprisingly unhelpful. Using a mutable type (like a list or dictionary) as a default argument and then modifying that argument can leads to Strang E results. It's usually best to avoid using mutable default arguments:to see why, try the following code locally.

Consider this function which the adds items to a todo list. Users can provide their own Todo list, or add items to a default list:

def todo_list (new_task, base_list=['wakeup'):    base_list.append (new_ Task)    return base_list

We can call the function as this:

>>> todo_list ("check the mail") ['wake up ' ' Check the Mail ']

If later on the We call it again:

>>> todo_list ("begin orbital Transfer")

The result is actully:

['wakeup'Check the mail'begin Orbital Transfer']

The list object is a base_list created once: when the todo_list function is defined. Lists is mutable objects. This list object was used every time the function is called, it isn ' t redefined each time the function is called. Because todo_list appends an item to the list, base_list can get longer each time this is todo_list called.

[Python] Problem with Default Arguments

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.