473,805 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1957
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__.MyDes c 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('attrib utes', None)
if attributes is not None:
for attrname, initval in attributes.iter items():
setattr(cls, attrname, MyDesc(attrname , initval))

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

class MySubclass(MyCl ass):
# let you override parent's attributes...
attributes = dict(attr1="oth erattr1", 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
1908
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 _get_attr(self): .... return self._attr .... attr = property(_get_attr) .... >>> a=A()
14
1649
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 object stood on itself instead of being an attribute to an other object. So what are the reasons for limiting this feature in such a way? -- Antoon Pardon
8
1622
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 tool. But I am confused by their behavior on instance of my class. I can only get the approximate behavior by using class variables. I am looking for something like:
0
10221
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 database table, using dynamic sql. Executing 'EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;' the error code -2149 is returned That means "Specified partition does not exist". Does anybody know if it is a database problem or a problem of
0
1313
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 objects returns functions, and classes > always call the __get__ methods of descriptors when those descriptors > are class attributes: Steven D'Aprano wrote: > Why all the indirection to implement something which is, conceptually, > the same as an...
12
1452
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, objtype=None): if obj is None: return self return getattr(obj, 'bar', 'no bar')
3
2172
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 for a member variable of a Python object. It has to be given a value when defined, or set within a method. But what is the difference between an Attribute of a Class, a Descriptor in a Class, and a Property in a Class?
5
3675
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 decorating the class/ property code), but I would like to do this at runtime. Is there another way to tell the PropertyGrid what editor to use for a
7
1355
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 example where you set an attribute s to a string and have another attribute l set automatically to its length.
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10613
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10368
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.