Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Correct

Unfortunately a lot of people still use it

(and it's actually correct, IF you don't modify it)

It's a risk not worth taking (to me, at least)



That's the only way of creating function with state without introducing closure or making an object with __call__. It's very handy for accumulators and other bits of state which are inherent to the function you write. It's essentially a `static` variable declared inside a function in C and believe it or not it has it's uses.

Depending on a problem it can be worthwhile to use other techniques of creating stateful callables, but that doesn't mean you should never create a function with mutable default argument. It's there in the language - learn about it, understand how it works and why it works like this, then understand where to use it and use it where it makes sense. That's a pretty generic advice, valid for almost any language feature.


> That's the only way of creating function with state without introducing closure or making an object with __call__

What about this?

  def foo():
      if not hasattr(foo, 'static_list'):
          foo.static_list = []
At least it's a bit easier to see that something funky is going on.




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

Search: