[Python] Why does PyCharm warn about mutable default arguments? How can I work around them?

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am using PyCharm (Python 3) to write a Python function which accepts a dictionary as an argument with attachment={}.

    def put_object(self, parent_object, connection_name, **data):
    ...

    def put_wall_post(self, message, attachment={}, profile_id="me"):
    return self.put_object(profile_id, "feed", message=message, **attachment)


    In the IDE, attachment={} is colored yellow. Moving the mouse over it shows a warning.


    Default arguments value is mutable

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

    Default argument values are evaluated only once at function definition time, which means that modifying the default value of the argument will affect all subsequent calls of the function.
    ​

    What does this mean and how can I resolve it?

    Continue reading...

Compartilhe esta Página