How to define a global array in python I want to define tm and prs as global array, and use them in two functions, how could I define them?
import numpy as np
import matplotlib.pyplot as plt
tm = []
prs = []
def drw_prs_tm(msg):
tm = np.append(tm,t)
prs = np.append(prs,s)
def print_end(msg):
plt.plot(tm,prs,'k-')
You need to refer them as global <var_name>
in the method
def drw_prs_tm(msg):
global tm
global prs
tm = np.append(tm,t)
prs = np.append(prs,s)
def print_end(msg):
global tm
global prs
plt.plot(tm,prs,'k-')
Read more on global
here and here
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With