Search code examples
pythonpylint

Undetected dangerous default value for mutable inside immutable (tuple of lists)


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.)


Solution

  • 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.