Problem:
I am trying to find a less clunky way to use (or accomplish something similar to) global variables. Right now I have all of my global variables in a file g.py, so I access them using g.var.
I would love to use var instead of g.var in my code, because I think it looks cleaner.
Details:
I have 3 files right now:
main.py: a small code for solving a PDEfunctions.py: a file that defines functions for applying boundary conditionsg.py: a file that has the variables that are modified when functions from functions.py are called
g.py:
import numpy as np
# variables
ap = np.float64(0.0)
awx = np.float64(0.0)
aex = np.float64(0.0)
rhs = np.float64(0.0)
functions.py:
import g
def bc_Neumann(i,m,nx):
m[0]=int(i); m[1]=int(i-1); m[2]=int(i+1);
if i==0:
m[1]=nx-1
g.ap=g.ap+g.awx
g.awx=0.0
if i==nx-1:
m[2]=0
g.ap=g.ap+g.aex
g.aex=0.0
return m
And main.py calls bc_Neumann() at some point.
Is there a better way to access g.ap, g.awx, etc.? I would like to just reference these global variables as ap, awx, etc.
from g import *. by using this method you can directly access the variables.from g import ap, awx. Is this what you're looking for?from g import ap, awxat the top of my files, I getUnboundLocalError: local variable 'ap' referenced before assignment. I can get rid of this error by addingglobal ap, awxin myfunctions.pyfile. But it seems like the actual values ofap,awxare not updated anymore. For example, I callm = bc_Neumann(i,m,nx)in my main code, but the value ofawxis not updated to0.0wheni=0.