0

I want to have 2 global arrays for results

global_array1 = []
global_array2 = []

In my function, I will add value to different array depends on condition:

def myfunc():
  global global_array1:
  global global_array2:

  result =[]

  for a in anArray:
      if some_condition == True:
          result = global global_array1
      else 
          result = global_array2

      # do something hhere
      result.append(aResult)

But when I try it, I don't see myFunction is saving result to the global array. How can I make 'result' as a pointer to either of my global_array1 or global_array2?

3
  • You have some syntax errors in your code... Commented Nov 21, 2012 at 20:14
  • to clarify; you shouldn't have colons after global blobal_array1 etc. Also, result = global global_array1 is a SyntaxError as well. Commented Nov 21, 2012 at 20:17
  • Global mutable data is bad style and often a source of subtle hard-to-spot bugs. How about just passing the "arrays" (that is, lists) as parameters and appending to them as needed? This way you'll see what your function really depends on. Commented Nov 21, 2012 at 20:18

2 Answers 2

3

This is pretty easy:

>>> def add(v,which):
...    c = a if which else b
...    c.append(v)
... 
>>> a = []
>>> b = []
>>> add(1,True)
>>> add(2,True)
>>> add(3,False)
>>> a
[1, 2]
>>> b
[3]

This however seems like a pretty fragile code design. Functions with side effects are usually not desirable (unless they're being used as instance methods on a class or something -- And then they should only modify the instance they are bound to...i.e. self).

Functions which modify global data are even more scary. It's usually better to pass the data into your function as an argument and have your function return a modified version. Modification of an argument in place is OK too, but only if your function returns None and the documentation is clear.

Sign up to request clarification or add additional context in comments.

Comments

0

The following, which is similar to your code, but actually runs, seems to work just fine:

global_array1 = []
global_array2 = []

def myfunc(aResult, anArray):
  global global_array1
  global global_array2

  for a in anArray:
      if a:
          result = global_array1
      else:
          result = global_array2

      # do something hhere
      result.append(aResult)

anArray = [True, True, False]

myfunc(1, anArray)
myfunc(2, anArray)
myfunc(3, anArray)

print 'global_array1:', global_array1
print 'global_array2:', global_array2

Output:

global_array1: [1, 1, 2, 2, 3, 3]
global_array2: [1, 2, 3]

1 Comment

@mgilson: That wasn't the question so I don't think it's relevant. I tried to keep my code similar to OP's.

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.