Wednesday, 18 September 2013

Is there an equivalent to @property for containers in Python?

Is there an equivalent to @property for containers in Python?

I'm writing a simplified wrapper class in Python for an AWS module (Boto,
specifically). Several times in this process I've used @property to avoid
special "getter" and "setter" methods in my library - I'm told that this
is the more pythonic way to do it. When using the class, the programmer
call the methods as if they were simple objects, like this:
myclass.myprop = 5 # sends "5" to myprop's setter function
result = myclass.myprop # calls myprop's getter function and stores the
result
But I'm also dealing with several sets of objects - name/value pairs of
tags, for example - that I would like to access as if they were held in a
container, possibly a dictionary or a list. Taking the tag example:
myclass.tags["newkey"] = "newvalue" # runs a function that applies tag
in AWS
result = myclass.tags["newkey"] # accesses AWS to get value of
"newkey" tag
From what I'm seeing, it looks like it would be possible to do this by
subclassing dict, but I feel like I'm missing something here. What is the
most pythonic way to create an interface like this?

No comments:

Post a Comment