[Tutor] Confused about globals
Dustin Mitchell
dustin at ywlcs.org
Fri Jun 9 16:19:42 CEST 2006
As a note, the "import" should be
import shared_funcs
In Python, most globals aren't really global -- they're local to the
module. If you split your modules by functionality, then variables
should naturally relate to a specific module, and be located there.
So, for example, you could move those global variables to
shared_funcs.py, renamed to wells.py:
=== wells.py ==
DE={}
DN={}
def get_xy_data():
in_file=open("well_xy.txt","r")
for line in in_file
L=line.split()
well=L[0]
x=L[1]
y=L[2]
DE[well]=x
DN[well]=y
in_file.close()
def lookup_well(well):
return (DE.get(well, None), DN.get(well, None))
=== main.py ===
import wells
def func_that_needs_wells():
...
for e n wells.DE.keys():
...
...
etc.
On Jun 9, 2006, at 4:42 AM, Etrade Griffiths wrote:
> Hi
>
> I have a series of python programs that plot stuff using PYX. Common
> to
> these is the need to read in a list of (well) locations in (X,Y)
> coords so
> I put that code in a separate module called shared_funcs.py. The
> coords
> are stored in dictionaries which I want to use later in the "main"
> program
> - every time I find a well with data, I can get the well's (x,y)
> coords by
> looking up the well name in the dictionary. The code snippet looks
> like this:
>
> === main.py ====
>
> # define coord dictionaries for global use
>
> DE={}
> DN={}
>
> import shared_funcs()
>
> shared_funcs.get_xy_data() # Get coords from file
>
> ... do plotting stuff
>
>
> === shared_funcs.py ===
>
> def get_xy_data():
> in_file=open("well_xy.txt","r")
> for line in in_file
> L=line.split()
> well=L[0]
> x=L[1]
> y=L[2]
>
> DE[well]=x
> DN[well]=y
> in_file.close()
>
> The problem is that DE and DN appear not to be accessible to
> get_xy_data -
> presumably this is because shared_funcs.py and main.py don't share the
> same
> scope. So, is there any way to let get_xy_data change DE and DN? I
> guess
> the obvious way is to pass them to get_xy_data as arguments - but is
> there
> a more "pythonic" method? Thanks in advance!
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list