Adding a list of descriptors to a class

  • Thread starter Bruno Desthuilliers
  • Start date
B

Bruno Desthuilliers

Marc 'BlackJack' Rintsch a écrit :
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))
Traceback (most recent call last):
new MyDesc
new MyDescnew MyDesc
new MyDesc
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...
 
B

Bruno Desthuilliers

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
 
B

Bob B.

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
 
M

Marc 'BlackJack' Rintsch

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
 
S

Steven Bethard

Bob said:
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.::
... pass
...
>>> for attr in ['attr1', 'attr2']:
... setattr(MyClass, attr, MyDesc(attr))
... 'blah'

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


HTH,

STeVe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top