Skip to content

Considered bad practice to use mutable objects as kwargs #23

Description

@Nintorac

Why it's bad - an initial call may alter the object and subsequent calls will have different results. see function a which has an ever increasing list and function c who's dictionary gets new entries on each call.

See example

>>> def a(b=[]):
...  print(b)
...  b+=[1]
... 
>>> a()
[]
>>> a()
[1]
>>> a()
[1, 1]
>>> a()
[1, 1, 1]
>>> a()
[1, 1, 1, 1]
>>> 
>>> 
>>> 
>>> def c(d={}):
...  d[len(d)]=1
...  print(d)
... 
>>> c()
{0: 1}
>>> c()
{0: 1, 1: 1}
>>> c()
{0: 1, 1: 1, 2: 1}
>>> c()
{0: 1, 1: 1, 2: 1, 3: 1}

reccomended workaround

def a(b=None):
  b = b or []

def c(d=None):
  d = d or {}

Though TBH the only time this has stung me is in an interview >.<

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions