473,545 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__slots__ and class attributes

I'm running into a something unexpected for a new-style class
that has both a class attribute and __slots__ defined. If the
name of the class attribute also exists in __slots__, Python
throws an AttributeError. Is this by design (if so, why)?

class A( object ):
__slots__ = ( 'value', )
value = 1

def __init__( self, value = None ):
self.value = value or A.value

a = A()
print a.value
Traceback (most recent call last):
File "t1.py", line 8, in ?
a = A()
File "t1.py", line 6, in __init__
self.value = value or A.value
AttributeError: 'A' object attribute 'value' is read-only
Nov 3 '05 #1
2 4967
Ewald R. de Wit wrote:
I'm running into a something unexpected for a new-style class
that has both a class attribute and __slots__ defined. If the
name of the class attribute also exists in __slots__, Python
throws an AttributeError. Is this by design (if so, why)?

class A( object ):
__slots__ = ( 'value', )
value = 1

def __init__( self, value = None ):
self.value = value or A.value

a = A()
print a.value
Traceback (most recent call last):
File "t1.py", line 8, in ?
a = A()
File "t1.py", line 6, in __init__
self.value = value or A.value
AttributeError: 'A' object attribute 'value' is read-only


Check the documentation on __slots__[1]:

__slots__ are implemented at the class level by creating descriptors
(3.3.2) for each variable name. As a result, class attributes cannot be
used to set default values for instance variables defined by __slots__;
otherwise, the class attribute would overwrite the descriptor assignment.

I agree that the error you get is a bit confusing. I think this has to
do with how the descriptor machinery works. When you write something like
a.value
where a is a class instance, Python tries to invoke something like:
type(a).value._ _get__(a)
Here's an example of that, working normallly:

py> class A(object):
.... __slots__ = ['value']
.... def __init__(self):
.... self.value = 1
....
py> a = A()
py> type(a).value
<member 'value' of 'A' objects>
py> type(a).value._ _get__
<method-wrapper object at 0x0129A1B0>
py> type(a).value._ _get__(a)
1

Now when you add a class attribute called 'value', you overwrite the
descriptor. So when Python tries to do the same thing (because your
definition of __slots__ makes it assume that 'value' is a descriptor),
the descriptor machinery raises an AttributeError:

py> class A(object):
.... __slots__ = ['value']
.... value = 1
....
py> a = A()
py> type(a).value
1
py> type(a).value._ _get__
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
AttributeError: 'int' object has no attribute '__get__'

This AttributeError must be somehow caught by the __slots__ machinery
and interpreted to mean that you tried to write to a read-only
attribute. The resulting error message is probably not what you want,
but I don't know the source well enough to figure out whether or not a
better error message could be given.
But why do you want a class level attribute with the same name as an
instance level attribute? I would have written your class as:

class A(object):
__slots__ = ['value']
def __init__(self, value=1):
self.value = value

where the default value you put in the class is simply expressed as a
default value to the __init__ parameter.

Steve

[1]http://docs.python.org/ref/slots.html
Nov 3 '05 #2
Steven Bethard wrote:
But why do you want a class level attribute with the same name as an
instance level attribute? I would have written your class as:

class A(object):
__slots__ = ['value']
def __init__(self, value=1):
self.value = value

where the default value you put in the class is simply expressed as a
default value to the __init__ parameter.


Thanks for your explanation. The reason why I was doing it was
to have class-level defaults, so that one can easily adjust how
new instances will be made. I'm doing it now with capitilized
class attribute names to avoid the name clash.

--
-- Ewald
Nov 4 '05 #3

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

Similar topics

1
1982
by: anabell | last post by:
I have a code like this: sqlString = 'INSERT INTO ' + self.TableName + ' VALUES (' + self.TableFields + ')' self.cursor.execute(sqlString, self.__dict__) This works correctly. However, I'm applying __slots__ in my script. And doing so would need the above statement modified. How will __slots__ perform the same task defined above? Is...
5
2919
by: Jean Brouwers | last post by:
Classes using __slots__ seem to be quite a bit smaller and faster to instantiate than regular Python classes using __dict__. Below are the results for the __slots__ and __dict__ version of a specific class with 16 attributes. Each line in the tables shows the number of instances created so far, the total memory usage in Bytes, the CPU time...
3
1630
by: Nick Jacobson | last post by:
The __slots__ attribute of new-style classes can reduce memory usage when there are millions of instantiations of a class. So would a __slots__ attribute for functions/methods have a similar benefit? i.e. could a function using __slots__ use significantly less memory, and therefore run faster, if called millions of times? If so, it will...
7
1656
by: Porky Pig Jr | last post by:
Hello, I"m still learning Python, but going through the Ch 5 OOP of Nutshell book. There is discussion on __slots__, and my understanding from reading this section is that if I have a class Rectangle (as defined in some prior sections), and then I provide definition class OptimizedRectangle(Rectangle): __slots__ = 'width', 'heigth' I can...
2
1206
by: Don Taylor | last post by:
Hi: I am puzzled about the following piece of code which attempts to create a class that can be used as record or struct with a limited set of allowed attributes that can be set into an instance of the class. class RecordClass(object): __slots__ = def __init__(self, args): print "Initial slots = ", RecordClass.__slots__
1
2699
by: pascal.parent | last post by:
Hi, I try to define a (new-style) class who: - have a __slots__ defined to be strict attributes, - return None if the attribute is 'ok' but not set, or raise a 'normal' error if the attribute isn't in __slots__. This code runs, but is it the good way? Thanks.
5
4016
by: jm.suresh | last post by:
Hi all, .... __slots__ = .... .... __slots__ = .... .... __slots__ = .... Traceback (most recent call last): File "<stdin>", line 1, in <module>
3
1612
by: John Machin | last post by:
I have stumbled across some class definitions which include all/most method names in a __slots__ "declaration". A cut-down and disguised example appears at the end of this posting. Never mind the __private_variables and the getter/setter approach, look at the list of methods in the __slots__. I note that all methods in an instance of a...
19
4621
by: jsanshef | last post by:
Hi, after a couple of days of script debugging, I kind of found that some assumptions I was doing about the memory complexity of my classes are not true. I decided to do a simple script to isolate the problem: class MyClass: def __init__(self,s): self.mystring = s
0
7689
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. ...
0
7786
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6022
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...
1
5359
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...
0
5076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3490
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...
1
1919
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
1
1044
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
743
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.