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

More like this:

  def f():
      x = 1
      def g():
          x = 2 # creates new local variable x
          # no way to assign new value to x in enclosing scope!


I'm probably naive for even asking, but why would you want to be able to change the value of x in the enclosing scope, unless you passed in a reference to it to g() (which doesn't exactly even work, as Str and numericals are immutable). If you had to change the value of X, make it a return value of G and assign that within the enclosing scope.

I view this as a benefit - less accidental stamping on variables/etc. I wouldn't consider myself A+ #1 programmer by any stretch though. This sort of thing seems like it would enable too many 'side effects' though.


Lispy languages like to use this construct for all kinds of purposes. See the appendix at the end of http://paulgraham.com/icad.html for examples.

You can do this in Python too, but it requires a bit more work. Python is asymmetrical here; you can see a variable in an enclosing scope, and if it's a mutable object you can change it, but you cannot reassign the name.


Python 3 lets you use the statement 'nonlocal varname' and it will grab it from the outer scope, as well.


Ah, yes. I should have mentioned that I was talking about Python 2.x.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

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

Search: