0

I thought that I could update a variable declared at the top of a Python script from within a function, but that's not true. I manage to do that using global:

count = 0

def updateCount():
    global count
    print count
    count = (count+1)%10

for x in xrange(10):
    updateCount()

Is this the best way to handle this ( a function updating a variable at a higher level) ? What is the 'pythonic' way of dealing with this. global seems a bit loose.

Also, please let me know if this is already answered and I'll close the question. I've been reading quite a few answers already posted close to the issue, but not quite there.

4
  • 2
    Use the return value of functions: e.g. count = updateCount(count). For state that must be preserved (and perhaps mutated), consider objects to store such data. Commented Sep 13, 2013 at 0:13
  • 3
    Simply don't use a global variable. The language is deliberately designed to make it hard for you to reassign names in the global namespace in a function, so why fight it? Either reassign the global variable explicitly in the global scope, by writing updateCount to have a parameter and assigning count = updateCount(count), or use a mutable object with methods to change its own state (increment a count attribute in your case). Commented Sep 13, 2013 at 0:13
  • The most pythonic way is not use globals. Commented Sep 13, 2013 at 6:10
  • @user2246674 return value is the simplest solution so far, will use classes later Commented Sep 13, 2013 at 9:49

1 Answer 1

1

Multiple solutions exists, depending on what you want to achieve.

Some was already mentioned in the comments to your question:

  • Create a class. updateCount is a method, count is an attribute
  • Return value from updateCount instead of using global count

Also you can use

  • Closures
  • Generators

IMHO, the most "pytohnic" (read "cool") way could be to use generators, here's an example

def updateCount(x):
    count = 0
    for i in xrange(x):
        count = (count+1) % 10
        yield count

for i in updateCount(15):
    print i
Sign up to request clarification or add additional context in comments.

1 Comment

that's pretty cool. Am going to use user2246674's return value suggestion for now and later refactor and use a class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.