How to customize getattr(obj, prop) function ?

Ben Finney bignose+hates-spam at benfinney.id.au
Thu May 18 09:08:15 EDT 2006


[Please provide some context in your reply, so we know what questions
or comments you're replying to.]

"Pierre" <meyer.p at gmail.com> writes:

> I don't want to use getattr(object, property, default_value) because
> I'm using external code and I don't want to modify or patch it.

You can subclass the class you want to modify, and override its behaviour.

    class ScaryExternalThing(object):
        """ The external class we don't want to modify. """

    class OurModifiedFriendlyThing(ScaryExternalThing):
        """ Class for use by our code. """

        attr_defaults = {
            'foo': "eggs",
            'bar': "beans",
        }

        def __getattr__(self, name):
            """ Method invoked when getting an unknown attribute """

            value = attr_defaults.get(name, "spam")
            return value

-- 
 \     "Welchen Teil von 'Gestalt' verstehen Sie nicht?  [What part of |
  `\             'gestalt' don't you understand?]"  -- Karsten M. Self |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list