nayan32biswas / mongodb-odm

MongoDB-ODM, NOSQL databases in Python, designed for simplicity, compatibility, and robustness.
https://mongodb-odm.readthedocs.io
MIT License
19 stars 1 forks source link

Using mutable objects as default parameter values in class methods can lead to unexpected behavior #8

Closed artheadsweden closed 1 year ago

artheadsweden commented 1 year ago

In the Document class, several methods use {} as a default parameter value for a dictionary-type parameter. However, using mutable objects as default parameter values can lead to unexpected behavior because the object is only created once when the function is defined, not every time the function is called. This means that if the mutable object is modified within the function, the modification persists across multiple calls to the function that omit the parameter.

To avoid this potential issue, I suggest using None as the default parameter value and creating a new instance of the mutable object within the function if the parameter is None. Here's an example of how the find_raw method could be modified to avoid this problem:

@classmethod
def find_raw(
    cls,
    filter=None,
    projection=None,
    **kwargs
):
    if filter is None:
        filter = {}
    if projection is None:
        projection = {}
    # rest of method body
nayan32biswas commented 1 year ago

Thank you for raising the issue. We will solve this issue in the upcoming version after a certain level of R&D.

nayan32biswas commented 1 year ago

Hi @artheadsweden, we resolved the potential issue you raised. You are welcome to raise errors more like this.