Skip to content

python function parameters should not contain mutable objects #28

Open

Description

@alecklandgraf

see: https://github.com/tempodb/tempodb-python/blob/master/tempodb/client.py#L49

def get_series(self, ids=[], keys=[], tags=[], attributes={}):
can cause a bunch of issues since python will not allocate a new list for each get_series call.
would rewrite with:

def get_series(self, ids=None, keys=None, tags=None, attributes=None):
    if ids is None:
        ids = []
...

e.g.

In [78]: def test_params(x=[]):
   ....:         x.append(3)
   ....:         print x
   ....:

In [79]: test_params()
[3]

In [80]: test_params()
[3, 3]

In [81]: a = [1,2,3,4]

In [82]: test_params(a)
[1, 2, 3, 4, 3]

In [83]: test_params(a)
[1, 2, 3, 4, 3, 3]

In [84]: test_params()
[3, 3, 3]

Activity

  1. myagley commented on Sep 16, 2013

    @myagley
    Contributor

    We can certainly update this to reflect your example. However, we don't mutate those parameters inside the function. When do you see an issue in practice? Can you provide an example?

    Thanks!

  2. myagley commented on Sep 16, 2013

    @myagley
    Contributor

    Is this blowing up in PEP8?

  3. alecklandgraf commented on Sep 16, 2013

    @alecklandgraf
    Author

    We had some issues internally that were traced back to this where we were looping over a function and getting strange results. It's just one of python's gotchas.
    Something like this:

    def increment_list(l=[]):
        l.append(1)
        return l
    
    x = increment_list() # x = [1]
    y = increment_list() # y = x = [1, 1]
    x.append(2) # x = y = [1, 1, 2]
    z = increment_list([1]) # z = [1, 1]
    
    
    def increment_list_better(l=None):
        if l is None:
            l=[]
        l.append(1)
        return l
    
    x = increment_list_better() # x = [1]
    y = increment_list_better() # y = [1], x = [1]
    
  4. myagley commented on Sep 16, 2013

    @myagley
    Contributor

    Yeah. I'm trying to figure out how urgent this is for our client. I don't think our client exhibits this problem because we don't mutate the parameters. However it should be cleaned up. We'll get it updated for the next release. Thanks for pointing it out! Appreciate it.

  5. alecklandgraf commented on Sep 16, 2013

    @alecklandgraf
    Author

    Glad to help. Hope it saves a headache down the road.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions