Accessors in Python (getters and setters)

Simon Brunning simon at brunningonline.net
Thu Jul 13 08:35:03 EDT 2006


On 10 Jul 2006 05:51:02 -0700, mystilleef <mystilleef at gmail.com> wrote:
> I decided to change the name of an attribute. Problem is I've used the
> attribute in several places spanning thousands of lines of code. If I
> had encapsulated the attribute via an accessor, I wouldn't need to do
> an unreliable and tedious search and replace accross several source
> code files to achieve my goal. I could simply change the name of the
> attribute and move on. Well, I'm glad python has properties. It's a
> feature that should be advertised more, especially for large scale
> python development.

Something like this any use to you?

from warnings import warn
import sys

class MyClass(object):

    def _get_bad_name(self):
        caller = sys._getframe(1).f_code
        warn("bad_name deprecated, but is referred to in function %s
(line %s in module %s). Please refer to good_name" % (caller.co_name,
caller.co_firstlineno, caller.co_filename))
        return self.good_name

    def _set_bad_name(self, bad_name):
        caller = sys._getframe(1).f_code
        warn("bad_name deprecated, but is referred to in function %s
(line %s in module %s). Please refer to good_name" % (caller.co_name,
caller.co_firstlineno, caller.co_filename))
        self.good_name = bad_name

    def _del_bad_name(self):
        caller = sys._getframe(1).f_code
        warn("bad_name deprecated, but is referred to in function %s
(line %s in module %s). Please refer to good_name" % (caller.co_name,
caller.co_firstlineno, caller.co_filename))
        del self.good_name

    bad_name = property(_get_bad_name, _set_bad_name, _del_bad_name,
"bad_name deprecated, please refer to good_name")

def test():
    my_object = MyClass()
    my_object.bad_name = "This should issue a warning"
    print my_object.bad_name  # This too
    print my_object.good_name  # But this should be fine

if __name__ == '__main__':
    test()

-- 
Cheers,
Simon B,
simon at brunningonline.net,
http://www.brunningonline.net/simon/blog/



More information about the Python-list mailing list