-1

I am tryint to convert some of my python arrays to numpy arrays and have problems accessing a supposingly global np array in another module.

Module 1 (imports data):

import numpy as np
jobs_db = []

def read_all_data(date, filepath):

    global jobs_db
    jobs_db =          np.loadtxt(filepath+'jobs_input.csv', dtype=np.uint8, delimiter=",", skiprows=1)

Module 2 (uses data):

from Import_data import *

if __name__ == '__main__':

     read_all_data(180901, 'C:/Users/*********/')
     print(jobs_db)

However, when I execute the main method, the console shows an empty array while the array contains data when calling it whithin module 1. The problem does not occur if I use a python array instead of a numpy array.

Hendrik
  • 153
  • 1
  • 2
  • 18
  • 2
    Why are you using global variables here at all? Just return it from your function – juanpa.arrivillaga Nov 21 '18 at 20:26
  • Anyway, this is because you are using a starred import, which is essentially equivalent to `import Import_data; jobs_db = Import_data.jobs_db`, but now `jobs_db` has nothing to do with `Import_data.jobs_db`, except they happen to refer to the same object, but can be made to refer to other objects independently. Use the module, so `Import_data.jobs_db`, or better yet, don't use a global variable at all – juanpa.arrivillaga Nov 21 '18 at 20:28
  • But how come it works with a python array and not a numpy array? – Hendrik Nov 21 '18 at 21:06
  • What do you mean? It works in exactly the same way. – juanpa.arrivillaga Nov 21 '18 at 21:07
  • Try it for yourself, make your function just do `jobs_db = ['foo', 'bar']` – juanpa.arrivillaga Nov 21 '18 at 21:14
  • @juanpa.arrivillaga Actually, you're right, it works the same way if I do `jobs_db = ['foo', 'bar']` (the array is still empty in my Module 2. However, if i try `jobs_db.append(['foo','bar'])`, it shows the content in my module 2. – Hendrik Nov 22 '18 at 14:27
  • yes, of course, because the two *different variables* are happening to refer to the *same object*. But assignment to different another object won't affect the other variable. It's the same as `a = 'foo'; b = a; a = 'bar'; print(b)` will print `foo` – juanpa.arrivillaga Nov 22 '18 at 17:01
  • But again, you shouldn't be using global variables to begin with. It is a really bad practice leading to hard to maintain and hard to understand code. *Especially* if you are using mutable global state. Have a couple global "constants" can be forgiven, code relying on mutable global state should not pass any sensible code review. – juanpa.arrivillaga Nov 22 '18 at 17:02

1 Answers1

0

The answer to the question with explanation can be found here.

For my problem specifically, I should have imported the module 1 by stating import Import_data instead of from Import_data import * and then using Import_data.jobs_db to access the variable.

Hendrik
  • 153
  • 1
  • 2
  • 18