Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a global array in python

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-')
like image 263
lbjx Avatar asked Dec 20 '22 23:12

lbjx


1 Answers

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’.

like image 182
karthikr Avatar answered Dec 31 '22 02:12

karthikr