tags:

views:

84

answers:

5

I know that I can write:

foo = 'bar'
def update_foo():
  global foo
  foo = 'baz'

But do I really need two lines of code there? Python, alas, won't allow me to say

global foo = 'baz'

I could also mash the two lines together with the unfortunately repetitive

global foo; foo = 'baz'

Any other shortcuts? I'm on Python 2.6.5, but I'd be curious to hear responses for Python 3 as well.

+5  A: 

It's two statements, there aren't any other forms.

Ian Bicking
+1: It's just that way.
S.Lott
...only if you've sworn to only ever use barenames...;-).
Alex Martelli
+2  A: 

You could write it like this using the globals() dictionary:

def update_foo():
  globals()['foo'] = 'baz'

but I would just stick with the 2 lines or the separating with a ; approach.

mikej
True, although generally messing with `globals()` (and even more so `locals()`) is not recommended.
David Zaslavsky
From http://www.python.org/dev/peps/pep-0020/, "Explicit is better than implicit".
Evan Plaice
A: 

If it makes you feel better to put it all on one line...

global foo; foo = 'baz'
Evan Plaice
+3  A: 

You could use my favorite alternative to global (a pretty idiosyncratic taste...):

import sys
thismodule = sys.modules[__name__]
thismodule.foo = 'bar'

def update_foo():
  thismodule.foo = 'baz'

Once you've made the thismodule reference, you don't need to use global in this module, because you're always working with qualified names rather than bare names (a much better idea IMHO... but maybe in MHO only, I've not been able to convince Guido to supply thismodule [[or some other identifier with this functionality]] back when Python 3 was gestating).

Note that the first assignment to foo, at global level, can be done either with this explicit syntax, or by assigning to barename foo as you do in your code (I guess it's not surprising that my preference goes to the explicit form, though, in this case, just barely).

Alex Martelli
Giving the module a 'this' keyword? For some reason that just gives me the heebiejeebies. If I were Guido, I'd make global declarations include a giant red flashing warning sign.
Evan Plaice
A: 
def update_foo():
    globals().update(foo='baz')
gnibbler