1

I have a problem while modifying an NumPy array in depended module, that was previously defined in parrent module. I have checked, and it's modifying only localy in the function calc() How can I modify an NumPy array that was defined in other module, inside a function?

main_module.py

import numpy as np
from pprint import pprint
test_array = np.array([1, 2, 3])
pprint(test_array)

process.py

from main_module import *
def calc():
    global test_array
    test_array = np.append(test_array, [4])
    pprint(test_array)
calc()
pprint(test_array)

1 Answer 1

1

In python globals are global to the module, not to the whole program. The standard way to do something like this in an object oriented language is to attach the relevant array to some object for example:

main_module:

import numpy as np
from pprint import pprint

class GlobalArrayHolder(object):
    def __init__(self):
        self.test_array = np.array([1, 2, 3])

arrayholder = GlobalArrayHolder()
pprint(arrayholder.test_array)

process:

import numpy as np
from pprint import pprint
from main_module import arrayholder

def calc(arrayholder):
    arrayholder.test_array = np.append(arrayholder.test_array, [4])
    pprint(arrayholder.test_array)

calc(arrayholder)
pprint(arrayholder.test_array)

If you don't want to define your own class for this you can use a simple built in class like a dict. For example:

main_module:

import numpy as np
from pprint import pprint

arrayholder = {'test_array':np.array([1, 2, 3])}
pprint(arrayholder['test_array'])

process:

import numpy as np
from pprint import pprint
from main_module import arrayholder

def calc(arrayholder):
    arrayholder['test_array'] = np.append(arrayholder['test_array'], [4])
    pprint(arrayholder['test_array'])

calc(arrayholder)
pprint(arrayholder['test_array'])
Sign up to request clarification or add additional context in comments.

Comments

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.