I'm designing a language with Pythonesque syntax, including casual creation of variables by assignment. I'm wondering at the moment exactly how to deal with assignment to global variables (and object/class variables, since I'm implementing classes as scopes). In Python itself, by default the attempt will create a local variable instead:

x = 1
def f():
    x = 2 # creates a local variable

but you can override this with a global declaration:

x = 1
def f():
    global x
    x = 2 # updates the global variable

I'm going to implement a prefix . for referring to variables in outer scopes (somewhat akin to prefix :: in C++, but will probably jump one scope instead of all), so that could be written as:

x = 1
def f():
    .x = 2 # updates the global variable

Would it be better to have just that one way of doing things, or would it be clearer or more convenient to have the mechanism of declaring variables as global the way Python does it?

  • 2
    I for one am a huge fan of the Python way. If you have to assign to non-local variables so often it warrants syntactic sugar, you're doing something wrong - and a language should rather focus on making good things easy. – user7043 May 12 '12 at 17:37
  • 1
    Yeah, you want to make the common case, the simple, more terse case and reserve the more complex syntax for things that should be more rare. Python does an extremely good job of doing this. – Gort the Robot May 12 '12 at 17:40

Python 3.x introduces the nonlocal statement, which is described by its documentation:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

PEP 3104 provides more background information about the motivation behind this feature.

I would consider this an unusual thing to do, so I don't mind having an explicit declaration that I'm doing something out of the ordinary. Having a concise single-character notation for this would not be useful to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.