[Tutor] Confused about globals
Kent Johnson
kent37 at tds.net
Fri Jun 9 16:44:42 CEST 2006
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.
You don't need a global variable in shared_funcs.get_xy_data() at all.
It is reading a file and creating two dicts. I would write it to create
and return the dicts. Then you can save them where you like in the
caller. Also, I would use one dict whose values are (x, y) pairs, rather
than two parallel dicts. Then your code looks like this:
=== shared_funcs.py ===
def get_xy_data():
D = {}
in_file=open("well_xy.txt","r")
for line in in_file
L=line.split()
well=L[0]
x=L[1]
y=L[2]
D[well]=(x, y)
in_file.close()
return D
=== main.py ===
import shared_funcs
D = shared_funcs.get_xy_data()
though I suggest a more descriptive name than D...
If there are other related bits of data or operations other than lookup,
that might point to using a class to wrap the dict, the other data and
operations.
Kent
More information about the Tutor
mailing list