Skip to content

rethink default values #8

@rue-a

Description

@rue-a

Currently, many default values are set to None by proxy (e.g., "", [], {}) to be compliant with the given type hint, e.g.

def method(in: str = "", in_2: list = []) -> str:
    <...>
    if <something>:
        return "some string"
    else:
        return ""

instead of:

def method(in: str = None, in_2: list = None) -> str:
    <...>
    if <something>:
        return "some string"
    else:
        return None

According to PyLint some of these default values may be harmful:

dangerous-default-value / W0102

Message emitted:

Dangerous default value %s as argument

Description:

Used when a mutable value as list or dictionary is detected in a default value for an argument.

Problematic code:

def whats\_on\_the\_telly(penguin\=\[\]):  \# \[dangerous-default-value\]
   penguin.append("property of the zoo")
   return penguin

Correct code:

def whats\_on\_the\_telly(penguin\=None):
   if penguin is None:
       penguin \= \[\]
   penguin.append("property of the zoo")
   return penguin

Additional details:

With a mutable default value, with each call the default value is modified, i.e.:

whats\_on\_the\_telly() \# \["property of the zoo"\]
whats\_on\_the\_telly() \# \["property of the zoo", "property of the zoo"\]
whats\_on\_the\_telly() \# \["property of the zoo", "property of the zoo", "property of the zoo"\]

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is neededinvalidThis doesn't seem rightpossible problemMay result in a problem

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions