Hacker News new | past | comments | ask | show | jobs | submit login

5.1: I prefer to use the rule "don't mutate objects" instead. I would've defined the example as:

  def function(item, stuff=[]):
      print stuff + [item]
Mutating the passed-in 'stuff' creates a leaky abstraction that then has to be documented. In rare cases this is what you want, but most of the time you're better off creating new objects and working with them. There's less to remember in the API, and fewer ways to screw up.

In particular, this code - which looks safe - blows up horribly with the article's function:

   MODULE_LEVEL_CONSTANT = ['foo', 'bar']
   function('baz', MODULE_LEVEL_CONSTANT)
   function('quux', MODULE_LEVEL_CONSTANT)
The second call will print ['foo', 'bar', 'baz', 'quux'] instead of the expected ['foo', 'bar', 'quux'].



Not for me...

  >>> def function(item, stuff=[]):
        print stuff + [item]

  >>> MODULE_LEVEL_CONSTANT = ['foo', 'bar']
  >>> function('baz', MODULE_LEVEL_CONSTANT)
  ['foo', 'bar', 'baz']
  >>> MODULE_LEVEL_CONSTANT
  ['foo', 'bar']
  >>> function('quux', MODULE_LEVEL_CONSTANT)
  ['foo', 'bar', 'quux']
I think you're confusing + and .append (the latter affects the object).


I believe he was referring to use of .append by the author. You defined it the way he recommends, which has the desired behavior.


Huh? I expect ['foo', 'bar', 'baz', 'quux']. I expect accumulation, esp with a list. If I wanted ['foo', 'bar', 'quux'] I would send in a fresh copy of a list instead of a list I'd been whoring around to other functions.

    function('baz', list(MODULE_LEVEL_CONSTANT))
    function('quux', list(MODULE_LEVEL_NOT_CONSTANT))
I would also change MODULE_LEVEL_CONSTANT to not say CONSTANT cause a list is no such thing and doesn't become constant just cause a label says so. Maybe it even leads people to expect silly things.


I dunno, the Python convention is "if you don't mutate, return a value; if you do mutate, return None." Since you wrote function('baz', MODULE_LEVEL_CONSTANT) without an assignment in front of it, I would assume that function must mutate something. Since strings are immutable, that just leaves either the display (print) or the second argument. I guess the real point is don't mutate your arguments and print them. Do one or the other, but not both.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: