define
Alex Martelli
aleax at aleax.it
Fri May 9 08:22:15 EDT 2003
<posted & mailed>
Turhan Ozen wrote:
> I have a long list of parameters. I want to keep them in an array in
> order to pass them to functions. But I want to use the name of each
> parameter in the formulas to make them easy to read. I can use x[index]
> in the formulas. I am trying to have another name for each x[index]. If
> I do anything to this secondary reference, the same is done to the
> corresponding x[index].
>
> It is possible to do this in C and it looks more readable.
It looks to me that a good solution is a "list with named items" class.
E.g., in Python 2.3 (warning, untested code):
class list_with_names(list):
def __init__(self, names):
list.__init__(self, len(names)*[None])
self.__names = {}
for i, name in enumerate(names):
self.__names[name] = i
def __getattr__(self, name):
try: return self.__names[name]
except KeyError: raise AttributeError
def __setattr__(self, name, value):
try: self[self.__names[name]] = value
except LookupError: object.__setattr__(self, name, value)
So instead of keeping your values in an 'array' (?), you'll do:
# e.g. a list of 5 items
x = list_with_names('aname another yetanother onemore andthistoo')
and then you can access and/or set e.g. x[1] equivalently to
x.another. Why you would want to use indexed access as well as
named access, I don't know, but surely it's MUCH clearer and more
readable if any access on an item of x does use x.something rather
than just a bare unqualified 'something' as the name!
Alex
More information about the Python-list
mailing list