A failed attempt to combine __getattr__ with properties

David Casti david at neosynapse.net
Wed Feb 5 09:50:34 EST 2003


I have a class which is used to stage information before it is loaded
into a database.  One of the dictionaries in this class manages the
fields, values, and constraints.  For example, if the dictionary
contained --

{ 'name': { 'value': 'Name', 'maxlen': 10, 'typname': 'varchar' } }

-- then there would be a column in the database named 'name', using
the varchar datatype, with a maximum length of 10.

I have created a __getattr__ function which creates get_ and set_
accessor functions on demand.  For example, there is no need to
explicitly declare get_name and set_name, because __getattr__ will
automatically create get & set functions to do type coercion, etc.  So
far, this system has worked out very well.

Now I'm working with an application which involves taking input from a
web page and updating a table.  If I was stupid, I'd just say
something like --

    eval ( "self.set_%s( %s )" % ( col, value ) )

-- but I can't trust web input, so 'eval'ing is right out.  I have
thought of using properties.  So, I have tried --

   name = property( get_name, set_name )

-- in my class definition, but this fails at compile time because
get_foo is not defined.

Is there a better way to approach this problem?




More information about the Python-list mailing list