Python Forum
mutable argument in function definition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
mutable argument in function definition
#2
This is what you are doing:
default_target = []
def append_to(item, target=default_target):
    target.append(item)
    return target
When the module is first imported, a list object is created to serve as the default value for target. I explicitly do that in my example above, but functionally it is the same as what happens in your example. If you want a different list each time the function is called you need to do this:
def append_to(item, target=None):
    return [item] if target is None else target.append(item)
But you should reconsider wanting to do this at all. I'm having a hard time thinking of a use case where I want a default mutable argument that is returned as the value of the function.
Reply


Messages In This Thread
RE: mutable argument in function definition - by deanhystad - Dec-15-2023, 02:00 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  using mutable in function defintion as optional paramter akbarza 8 678 Apr-27-2024, 09:59 PM
Last Post: snippsat
  class definition and problem with a method HerrAyas 2 382 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  error occuring in definition a class akbarza 3 848 Nov-26-2023, 09:28 AM
Last Post: Yoriz
  determine parameter type in definition function akbarza 1 666 Aug-24-2023, 01:46 PM
Last Post: deanhystad
  [split] Explain the python code in this definition Led_Zeppelin 1 803 Jan-13-2023, 10:20 PM
Last Post: deanhystad
Information How to take url in telegram bot user input and put it as an argument in a function? askfriends 0 1,216 Dec-25-2022, 03:00 PM
Last Post: askfriends
  i want to use type= as a function/method keyword argument Skaperen 9 2,076 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  Explain the python code in this definition Led_Zeppelin 1 1,171 Oct-27-2022, 04:04 AM
Last Post: deanhystad
  mutable values to string items? fozz 15 3,175 Aug-30-2022, 07:20 PM
Last Post: deanhystad
  meaning of -> syntax in function definition DrakeSoft 5 2,125 Apr-09-2022, 07:45 AM
Last Post: DrakeSoft

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020