data strucutures in python

Andrew Dalke dalke at
Wed Sep 20 07:30:29 CEST 2000

Matthew Banham:
>I have a list of tuples of the form (variablename, variableFunction).
>In Python, if I type:-
>variablename = data then variableFunction gets called with data passed to
>it. For example say I have:-
>p = 'lambda', ChangeLambdaFunc
>and I type the line:-
>lambda = 10
>then the above line gets implemented as:-

How about something like the following (untested) code?

_conversions = {
  "lambda": ("GetLambdaValue", "ChangeLambdaFunc"),
  "readonly": ("GetSomeData", None),
  "writeonly": (None, "SetSomeData),

class Spam:
  def __getattr__(self, name):
    funcs = _conversions.get(name)
    if funcs is None:
        raise AttributeError, name
    getter_name = funcs[0]
    if getter_name is None:
        raise TypeError, "write-only value"
    return getattr(self, getter_name)()
  def __setattr__(self, name, value):
    funcs = _conversions.get(name)
    if funcs is None:
        self.__dict__[name] = value
        setter_name = funcs[1]
        if setter_name is None:
            raise TypeError, "read-only value"
        getattr(self, setter_name)(value)

spam = Spam()
print spam.lambda
print spam.readonly
print spam.writeonly  # should give a TypeError

                    dalke at

More information about the Python-list mailing list