473,395 Members | 1,537 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Adding a list of descriptors to a class

I've been playing with descriptors lately. I'm having one problem I
can't seem to find the answer to. I want to assign a descriptor to a
list of attributes. I know I should be able to add these somewhere in
the class's __dict__, but I can't figure out where. Here's some code:

class MyDesc(object):
def __init__(self, name=None, initVal=None):
self.name = name
self.value = initVal

def __get__(self, obj, objtype):
// Do some stuff
self.value = "blah"
return self.value

class MyClass(object):
attributes = ('attr1', 'attr2')
for attr in attributes:
exec ("%s=MyDesc('%s')") % (attr, attr)

// More stuff in the class

Ok, that "exec" is an ugly hack. There's gotta be someway to plop
this straight into the class's __dict__ without doing that, but when I
try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
__init__ method, I get the error: "TypeError: 'dictproxy' object does
not support item assignment"

Any ideas?

Thanks,
Bob

Aug 7 '07 #1
5 1941
On Tue, 07 Aug 2007 09:25:32 -0700, Bob B. wrote:
Ok, that "exec" is an ugly hack. There's gotta be someway to plop
this straight into the class's __dict__ without doing that, but when I
try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
__init__ method, I get the error: "TypeError: 'dictproxy' object does
not support item assignment"
Does ``setattr(self.__class__, attr, MyDesc(attr))`` work?

Ciao,
Marc 'BlackJack' Rintsch
Aug 7 '07 #2
Bob B. wrote:
I've been playing with descriptors lately. I'm having one problem I
can't seem to find the answer to. I want to assign a descriptor to a
list of attributes. I know I should be able to add these somewhere in
the class's __dict__, but I can't figure out where. Here's some code:

class MyDesc(object):
def __init__(self, name=None, initVal=None):
self.name = name
self.value = initVal

def __get__(self, obj, objtype):
// Do some stuff
self.value = "blah"
return self.value

class MyClass(object):
attributes = ('attr1', 'attr2')
for attr in attributes:
exec ("%s=MyDesc('%s')") % (attr, attr)

// More stuff in the class

Ok, that "exec" is an ugly hack. There's gotta be someway to plop
this straight into the class's __dict__ without doing that, but when I
try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
__init__ method, I get the error: "TypeError: 'dictproxy' object does
not support item assignment"
Probably the simplest thing is to just add the attributes after the
class body, e.g.::
>>class MyClass(object):
... pass
...
>>for attr in ['attr1', 'attr2']:
... setattr(MyClass, attr, MyDesc(attr))
...
>>c = MyClass()
c.attr1
'blah'

Another option would be to use a metaclass to set the class attributes
at class creation time::
>>class Meta(type):
... def __init__(cls, name, bases, bodydict):
... for attr in cls._desc_attrs:
... setattr(cls, attr, MyDesc(attr))
...
>>class MyClass(object):
... __metaclass__ = Meta
... _desc_attrs = ['attr1', 'attr2']
...
>>c = MyClass()
c.attr1
'blah'
HTH,

STeVe
Aug 7 '07 #3
Probably the simplest thing is to just add the attributes after the
class body, e.g.::
>>class MyClass(object):
... pass
...
>>for attr in ['attr1', 'attr2']:
... setattr(MyClass, attr, MyDesc(attr))
...
>>c = MyClass()
>>c.attr1
'blah'
That worked. Thanks.
Aug 7 '07 #4
Marc 'BlackJack' Rintsch a écrit :
On Tue, 07 Aug 2007 09:25:32 -0700, Bob B. wrote:

>>Ok, that "exec" is an ugly hack. There's gotta be someway to plop
this straight into the class's __dict__ without doing that, but when I
try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
__init__ method, I get the error: "TypeError: 'dictproxy' object does
not support item assignment"


Does ``setattr(self.__class__, attr, MyDesc(attr))`` work?
In the __init__() ?

Yes indeed, it works. But it means that:
1/ the attributes are not set on the class before it has been
instanciated at least once
2/ each time you instanciate the class, the attributes are rebound to
new MyDesc instances

class MyDesc(object):
def __init__(self, name=None, initVal=None):
self.name = name
self.value = initVal
print "new %s" % self.__class__.__name__

def __get__(self, obj, objtype):
# Do some stuff
#self.value = "blah"
if obj is None:
return self
return self.value

class Marc(object):
attributes = ('toto', 'tata')
def __init__(self):
cls = self.__class__
for attr in cls.attributes:
setattr(cls, attr, MyDesc(attr, attr))
>>Marc.toto
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'Marc' has no attribute 'toto'
>>m1 = Marc()
new MyDesc
new MyDesc
>>Marc.toto
<__main__.MyDesc object at 0x4033846c>
>>t = _
m2 = Marc()
new MyDesc
new MyDesc
>>Marc.toto is t
False
>>>
So while it "works" (kinda), I would not recommand this solution. Even
if you do test for the existence of the attribute before rebinding it,
you'll have to go thru the whole dance each time you instanciate the class.

My 2 cents...
Aug 7 '07 #5
Bob B. a écrit :
I've been playing with descriptors lately. I'm having one problem I
can't seem to find the answer to. I want to assign a descriptor to a
list of attributes. I know I should be able to add these somewhere in
the class's __dict__, but I can't figure out where. Here's some code:

class MyDesc(object):
def __init__(self, name=None, initVal=None):
self.name = name
self.value = initVal

def __get__(self, obj, objtype):
// Do some stuff
self.value = "blah"
return self.value

class MyClass(object):
attributes = ('attr1', 'attr2')
for attr in attributes:
exec ("%s=MyDesc('%s')") % (attr, attr)

// More stuff in the class

Ok, that "exec" is an ugly hack. There's gotta be someway to plop
this straight into the class's __dict__ without doing that, but when I
try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
__init__ method, I get the error: "TypeError: 'dictproxy' object does
not support item assignment"

Any ideas?
Steven already show you the simplest solution. Now if you want something
"cleaner" (or at least more transparent to persons subclassing MyClass -
which may or may not be a concern), you can use metaclasses too:

class MyDesc(object):
def __init__(self, name=None, initVal=None):
self.name = name
self.value = initVal

def __get__(self, obj, objtype):
# Do some stuff
#self.value = "blah"
if obj is None:
return self
return self.value

class MyType(type):
def __init__(cls, name, bases, dic):
attributes = dic.get('attributes', None)
if attributes is not None:
for attrname, initval in attributes.iteritems():
setattr(cls, attrname, MyDesc(attrname, initval))

class MyClass(object):
__metaclass__ = MyType
attributes = dict(attr1="attr1", attr2="attr2")

class MySubclass(MyClass):
# let you override parent's attributes...
attributes = dict(attr1="otherattr1", attr3="a new one")
HTH
Aug 7 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Denis S. Otkidach | last post by:
I've noticed that the order of attribute lookup is inconsistent when descriptor is used. property instance takes precedence of instance attributes: >>> class A(object): .... def...
14
by: Antoon Pardon | last post by:
Can anyone explain why descriptors only work when they are an attribute to an object or class. I think a lot of interesting things one can do with descriptors would be just as interesting if the...
8
by: David S. | last post by:
I am looking for a way to implement the same simple validation on many instance attributes and I thought descriptors (http://users.rcn.com/python/download/Descriptor.htm) looked like the right...
0
by: Jan | last post by:
I store sql-commands in a database table. In the first step I get the sql command out of the database table with embedded sql. In the second step I try to execute the command, which i got from the...
0
by: Steven Bethard | last post by:
Steven Bethard wrote: > (For anyone else out there reading who doesn't already know this, > Steven D'Aprano's comments are easily explained by noting that the > __get__ method of staticmethod...
12
by: bruno at modulix | last post by:
Hi I'm currently playing with some (possibly weird...) code, and I'd have a use for per-instance descriptors, ie (dummy code): class DummyDescriptor(object): def __get__(self, obj,...
3
by: redefined.horizons | last post by:
I've been reading about Python Classes, and I'm a little confused about how Python stores the state of an object. I was hoping for some help. I realize that you can't create an empty place holder...
5
by: florin | last post by:
hi Is there a "simple" way to add attributes to a class/property at runtime? What I try to do is set the default editor for a class/property at runtime (I know I can set this very easy by...
7
by: mrkafk | last post by:
Hello everyone, I'm trying to do seemingly trivial thing with descriptors: have another attribute updated on dot access in object defined using descriptors. For example, let's take a simple...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.