LuTze
LuTze

Reputation: 71

global variable (matrix) in python

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

Upvotes: 1

Views: 1451

Answers (2)

DavidG
DavidG

Reputation: 25380

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]]

Upvotes: 1

Gilles Criton
Gilles Criton

Reputation: 781

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.

Upvotes: 0

Related Questions