Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
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. –  delnan 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. –  Steven Burnap May 12 '12 at 17:40
add comment

1 Answer

up vote 4 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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