variable hell
Robert Kern
rkern at ucsd.edu
Thu Aug 25 16:17:03 EDT 2005
Ron Garret wrote:
> In article <mailman.3516.1124987149.10512.python-list at python.org>,
> Robert Kern <rkern at ucsd.edu> wrote:
>
>> In the
>>bowels of my modules, I may not know what the contents are at code-time,
>
> Then how do you write your code?
With style. ;-)
I use a Bunch where I might otherwise use a dictionary inside my modules
because it *is* a dictionary. Interactively, I'll usually use it as an
object with attributes. The keys are usually ideosyncratic, like station
codes for permanent GPS stations (e.g. "CAND", "USLO", "MNMC", "MIDA"),
rather than generic (e.g. "northing", "day").
So I might have a function that do some analysis on all of the GPS
stations within a Bunch. I don't know the names of the stations when I'm
writing the function, but I can iterate over the keys and values in the
Bunch.
def subtract_reference(data, refstation):
"""Subtract the motion of the reference station from the remaining
timeseries.
"""
refdata = data[refstation]
for station in data:
if station == refstation:
continue
data[station].northing -= refdata.northing
data[station].easting -= refdata.easting
# ...
At the prompt, though, I may want to plot CAND's timeseries.
In [10]: plot(data.CAND.t, data.CAND.northing)
Bunch allows me to use "data[station]" and "data.CAND" as the situation
demands rather than forcing me to use the clunkier "getattr(data,
station)" or "data['CAND']", respectively.
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list