0

Why the following code does not trigger dangerous-default-value for items when using pylint? Is this an unintended feature of pylint (i.e. a bug)?

def func(item, items=([],)):
    items[0].append(item)
    return items

My understanding is that it should be all means do, since:

print(func(1))
# ([1],)
print(func(2))
# ([1, 2],)

Is there a standard way of sanitize this, or do I have to do it by myself?

(Note: This is just toy code to illustrate the issue.)

norok2
  • 25,683
  • 4
  • 73
  • 99
  • 1
    I suspect (though could be wrong) that pylint doesn't attempt to detect mutability of defaults beyond a fairly small set of common cases. – NPE Jul 23 '19 at 10:35
  • The [description](http://pylint-messages.wikidot.com/messages:w0102) for the dangerous default value warning is "Used when a mutable value as list or dictionary is detected in a default value for an argument.". A list inside a tuple doesn't meet that definition. – snakecharmerb Jul 23 '19 at 14:38

1 Answers1

0

It seems like pylint triggers dangerous-default-value only for non-nested list, dict and set, and this is a poorly documented behavior, since the behavior for set is omitted, while the following:

def func(item, items=set()):
    items[0].append(item)
    return items

will actually trigger the warning.


The FlyingCircus package offers a freeze() function for recursively sanitize (nested) combinations of list, dict and set containers.

Disclaimer: I am the main author of the package.

norok2
  • 25,683
  • 4
  • 73
  • 99