471,350 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,350 software developers and data experts.

setattr vs readonly property

hi,

My main purpose for using setattr(object, attr, value) for assign
values from a dict that has some keys that may not be present on some
object's attibute, which makes it work for me. My problem is dealing
with read only attribute like sample_attribute =
property(f_get=_get_sample_attribute). what approach should I use? Or
is my first approach In the first place right?

Thanks
james

Sep 12 '07 #1
2 2812
james_027 wrote:
hi,

My main purpose for using setattr(object, attr, value) for assign
values from a dict that has some keys that may not be present on some
object's attibute, which makes it work for me. My problem is dealing
with read only attribute like sample_attribute =
property(f_get=_get_sample_attribute). what approach should I use? Or
is my first approach In the first place right?
Since read-only properties are very concise written as this:
class Foo(object):
@property
def ro_prop(self):
return "whatever"

I'd say that's the way to go - using __getattr__ for this will lead to
rather convoluted code IHMO.

Diez
Sep 12 '07 #2
My main purpose for using setattr(object, attr, value) for assign
values from a dict that has some keys that may not be present on some
object's attibute, which makes it work for me. My problem is dealing
with read only attribute like sample_attribute =
property(f_get=_get_sample_attribute). what approach should I use? Or
is my first approach In the first place right?
You could try catching the exception thrown when you attempt to assign
to a read-only attribute. Although you may get consistency issues. ie
your object doesn't have all the details from the dict, but the
calling code expects them to be set. Perhaps you should provide
"setter" methods for the properties also, so that your objects
internal state gets set correctly.

eg: in your class declaration:

def setfoo(self, value):
# Add code here to check 'value' and set internal 'foo' state correctly
self._foo = value

def getfoo(self):
return self._foo

foo = property(setfoo, getfoo)
Sep 12 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Roberto | last post: by
reply views Thread by XIAOLAOHU | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.