1

I am trying to use a numpy matrix as a global variable. However, when I reference the function below in other scripts I only get "global_gABD = []" and "gABD = matrix([[1,6,6]])" in my variable table (see attached picture). My gABD is not saved as global variable.

def gABD():

   global gABD
   import numpy as np
   gABD = np.matrix((1,6,6))
gABD()

Is there a way to do this or can numpy.matrix not be used globally?

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82
LuTze
  • 61
  • 7
  • 6
    Your variable name is the same as your function... this seems like a bad idea – DavidG Feb 13 '18 at 09:44
  • 2
    What is a "variable table"? You can use anything you like as a global variable, although it's usually bad practice to do so; but note that your variable would overwrite your function since they have the same name. – Daniel Roseman Feb 13 '18 at 09:45
  • My python interpreter software (spyder) allows me to see variables that currently used. Similar to Matlab if you are familiar. – LuTze Feb 13 '18 at 09:50

2 Answers2

1

You can of course use global variables for this. However it is not considered good practice. You might want to read Why are global variables evil? Note, your variable and function have the same name, this will cause problems.

def gABD():

   global mat
   import numpy as np
   mat = np.matrix((1,6,6))
gABD()
print (mat)
# [[1 6 6]]

A better approach is to return the variable from your function so that it can be use elsewhere in the code:

def gABD():

   import numpy as np
   return np.matrix((1,6,6))

my_matrix = gABD()
print (my_matrix)
# [[1 6 6]]
DavidG
  • 24,279
  • 14
  • 89
  • 82
0

try this:

a = 25
b = 37
def foo():
    global a  # 'a' is in global namespace
    a = 10
    b = 0
foo()
# you should have now a = 10 and b= 37. If this simple example works, replace then a by your matrix.
Gilles Criton
  • 673
  • 1
  • 13
  • 27
  • Yeah, integers as global variables are fine (this works for me). But as soon as I replace the value with a matrix it will ignore the global declaration. Therefore "a" is 10 in your example but when I set "a" as a matrix it gives me 25. – LuTze Feb 13 '18 at 10:05
  • Ok, now try the example provided by Jacques: https://stackoverflow.com/questions/39964254/python-updating-global-variables – Gilles Criton Feb 13 '18 at 10:43