473,406 Members | 2,377 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,406 software developers and data experts.

a question on __slots__ (and example from Nutshell)

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 use the instance of OptimizedRectangle, say, x, with 'width' and
'heigth', but (quoting the book) 'any attempt to bind on x any
attribute whose name is not in C.__slots__ raises an exception.

Alas, something goes wrong here, but I *can* bind any arbitrary
attribute, and seems like the instance of OptimizedRectangle does have
its own __dict__ where those attributes are kept. I'm using the latest
stable version of Python (2.3.4, I believe). Here is a session from
IDLE:

Here I'm defining the class with __slots__:
class OptimizedRectangle(Rectangle): __slots__ = 'width', 'heigth'
and create its instance, 'ropt': ropt = OptimizedRectangle(4,5)
Note that __dict__ is still there: ropt.__dict__ {}

so I can define some arbitrary variable, say, newarea:
ropt.newarea = 15
which goes into the dictionary
ropt.__dict__ {'newarea': 15}

whereas width and heigth are still kept in __slots__: ropt.__slots__

('width', 'heigth')

My impression is that once __slots__ are defined, __dict__ is
effectively disabled - but in this example it's alive and well. Am I
missing anything here?

TIA.
Jul 18 '05 #1
7 1645
I'll bet this is because you are subclassing Rectangle
class that is an old-style class. Maybe one of the
other "experts" on this can confirm.

Larry Bates
Syscon, Inc.

"Porky Pig Jr" <po**********@my-deja.com> wrote in message
news:56**************************@posting.google.c om...
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 use the instance of OptimizedRectangle, say, x, with 'width' and
'heigth', but (quoting the book) 'any attempt to bind on x any
attribute whose name is not in C.__slots__ raises an exception.

Alas, something goes wrong here, but I *can* bind any arbitrary
attribute, and seems like the instance of OptimizedRectangle does have
its own __dict__ where those attributes are kept. I'm using the latest
stable version of Python (2.3.4, I believe). Here is a session from
IDLE:

Here I'm defining the class with __slots__:
class OptimizedRectangle(Rectangle): __slots__ = 'width', 'heigth'
and create its instance, 'ropt': ropt = OptimizedRectangle(4,5)
Note that __dict__ is still there: ropt.__dict__ {}

so I can define some arbitrary variable, say, newarea:
ropt.newarea = 15
which goes into the dictionary
ropt.__dict__ {'newarea': 15}

whereas width and heigth are still kept in __slots__: ropt.__slots__

('width', 'heigth')

My impression is that once __slots__ are defined, __dict__ is
effectively disabled - but in this example it's alive and well. Am I
missing anything here?

TIA.

Jul 18 '05 #2
The problem is that the __slots__ mechanism is a function of "new style
classes", which really should be renamed =) A new-style-class is any class
that inherits from "object" or one of its descendants.

You're inheriting from Rectangle. What is its definition? I bet its
something like:

class Rectangle:
def __init__(self): pass

Since OptimizedRectangle inherits from an old-style class, its an old-style
class... and __slots__ has no function.

So, just...

class Rectangle(object): pass

And OptimizedRectangle should work like you expect.

--Stephen

"Porky Pig Jr" <po**********@my-deja.com> wrote in message
news:56**************************@posting.google.c om...
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 use the instance of OptimizedRectangle, say, x, with 'width' and
'heigth', but (quoting the book) 'any attempt to bind on x any
attribute whose name is not in C.__slots__ raises an exception.

Alas, something goes wrong here, but I *can* bind any arbitrary
attribute, and seems like the instance of OptimizedRectangle does have
its own __dict__ where those attributes are kept. I'm using the latest
stable version of Python (2.3.4, I believe). Here is a session from
IDLE:

Here I'm defining the class with __slots__:
class OptimizedRectangle(Rectangle): __slots__ = 'width', 'heigth'
and create its instance, 'ropt': ropt = OptimizedRectangle(4,5)
Note that __dict__ is still there: ropt.__dict__ {}

so I can define some arbitrary variable, say, newarea:
ropt.newarea = 15
which goes into the dictionary
ropt.__dict__ {'newarea': 15}

whereas width and heigth are still kept in __slots__: ropt.__slots__

('width', 'heigth')

My impression is that once __slots__ are defined, __dict__ is
effectively disabled - but in this example it's alive and well. Am I
missing anything here?

TIA.

Jul 18 '05 #3
Nop, a class Rectangle is defined as a new style class. Nuthsell, page
85.
It is given as a part of discussion of 'properties', also part of new
style
classes.

My apologies for refering to the parent class, rather than providing
its complete definition. This is one of the golden rules when asking
for support: provide complete list of session -- and I did not. Mea
culpa.

Let me start all over. Here is the complete IDLE session,
except on a different machine with Python 2.3.3 rather than 2.3.4 but
I assume this shouldn't reallhy matter:

Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)]
on win32
Type "copyright", "credits" or "license()" for more information.

************************************************** **************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
************************************************** **************

IDLE 1.0.2
class Rectangle(object): # defined as new class def __init__(self, width, heigth):
self.width = width
self.heigth = heigth
def getArea(self):
return self.width * self.heigth
area = property(getArea, doc='area of the rectangle')

rect = Rectangle(4,5)
rect.area 20
class OptimizedRectangle(Rectangle): # subclass with __slots__ __slots__ = 'width', 'heigth'

optrec = OptimizedRectangle(3,4)
optrec.area 12 optrec.__dict__ # note that __dict__ shows up (why?) {} optrec.newarea = 12 # so I can define new attribute on a fly
optrec.newarea 12
optrec.__slots__ # slots are the part of instance ('width', 'heigth')
optrec.__dict__ # but so is the dict {'newarea': 12}


TIA.
Jul 18 '05 #4
*blink* That's interesting.

I've never tried to add __slots__ to 'optimize' a parent like that. It
doesn't actually surprise me that a child inherits everything with its
parent-- including the dictionary since one is there. And if one is there,
it doesn't surprise me that you can assign arbitrary attributes to it.

Its nothing I was aware of-- but it doesn't surprise me. I wouldn't expect
having __slots__ there to go in and remove something that was present in a
parent class.

--Stephen
"Porky Pig Jr" <po**********@my-deja.com> wrote in message
news:56**************************@posting.google.c om...
Nop, a class Rectangle is defined as a new style class. Nuthsell, page
85.
It is given as a part of discussion of 'properties', also part of new
style
classes.

My apologies for refering to the parent class, rather than providing
its complete definition. This is one of the golden rules when asking
for support: provide complete list of session -- and I did not. Mea
culpa.

Let me start all over. Here is the complete IDLE session,
except on a different machine with Python 2.3.3 rather than 2.3.4 but
I assume this shouldn't reallhy matter:

Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)]
on win32
Type "copyright", "credits" or "license()" for more information.

************************************************** **************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
************************************************** **************

IDLE 1.0.2
class Rectangle(object): # defined as new class def __init__(self, width, heigth):
self.width = width
self.heigth = heigth
def getArea(self):
return self.width * self.heigth
area = property(getArea, doc='area of the rectangle')

rect = Rectangle(4,5)
rect.area 20
class OptimizedRectangle(Rectangle): # subclass with __slots__ __slots__ = 'width', 'heigth'

optrec = OptimizedRectangle(3,4)
optrec.area 12 optrec.__dict__ # note that __dict__ shows up (why?) {} optrec.newarea = 12 # so I can define new attribute on a fly
optrec.newarea 12
optrec.__slots__ # slots are the part of instance ('width', 'heigth')
optrec.__dict__ # but so is the dict {'newarea': 12}


TIA.

Jul 18 '05 #5
Since types and classes are unified in the new object model,
the following line at the top of the source file will also
do the trick, even if you dont directly subclass from object.

__metaclass__ = object

class Rectangle... etc

-Anand
"Ixokai" <us****@ixokai.net> wrote in message news:<10*************@corp.supernews.com>...
The problem is that the __slots__ mechanism is a function of "new style
classes", which really should be renamed =) A new-style-class is any class
that inherits from "object" or one of its descendants.

You're inheriting from Rectangle. What is its definition? I bet its
something like:

class Rectangle:
def __init__(self): pass

Since OptimizedRectangle inherits from an old-style class, its an old-style
class... and __slots__ has no function.

So, just...

class Rectangle(object): pass

And OptimizedRectangle should work like you expect.

--Stephen

"Porky Pig Jr" <po**********@my-deja.com> wrote in message
news:56**************************@posting.google.c om...
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 use the instance of OptimizedRectangle, say, x, with 'width' and
'heigth', but (quoting the book) 'any attempt to bind on x any
attribute whose name is not in C.__slots__ raises an exception.

Alas, something goes wrong here, but I *can* bind any arbitrary
attribute, and seems like the instance of OptimizedRectangle does have
its own __dict__ where those attributes are kept. I'm using the latest
stable version of Python (2.3.4, I believe). Here is a session from
IDLE:

Here I'm defining the class with __slots__:
>> class OptimizedRectangle(Rectangle):

__slots__ = 'width', 'heigth'
and create its instance, 'ropt':
>> ropt = OptimizedRectangle(4,5)


Note that __dict__ is still there:
>> ropt.__dict__

{}

so I can define some arbitrary variable, say, newarea:
>> ropt.newarea = 15


which goes into the dictionary
>> ropt.__dict__

{'newarea': 15}

whereas width and heigth are still kept in __slots__:
>> ropt.__slots__

('width', 'heigth')

My impression is that once __slots__ are defined, __dict__ is
effectively disabled - but in this example it's alive and well. Am I
missing anything here?

TIA.

Jul 18 '05 #6
py*******@Hotpop.com (Anand Pillai) wrote in message news:<84**************************@posting.google. com>...
Since types and classes are unified in the new object model,
the following line at the top of the source file will also
do the trick, even if you dont directly subclass from object.

__metaclass__ = object


You mean __metaclass__ = type, isn't it?
Michele Simionato
Jul 18 '05 #7
"Ixokai" <us****@ixokai.net> wrote in message news:<10*************@corp.supernews.com>...
*blink* That's interesting.

I've never tried to add __slots__ to 'optimize' a parent like that. It
doesn't actually surprise me that a child inherits everything with its
parent-- including the dictionary since one is there. And if one is there,
it doesn't surprise me that you can assign arbitrary attributes to it.

Its nothing I was aware of-- but it doesn't surprise me. I wouldn't expect
having __slots__ there to go in and remove something that was present in a
parent class.

--Stephen

Well, the fact is that the whole example is from 'Python in a
nutshell', by Alex Martelli, 2003 edition, should be pretty much up to
date, unless of course something got changed between the time this
book was written (probably some earlier version of 2.3 was already in
place) and the current release (2.3.3+), or the whole example is
wrong.

I'll try to contact the author directly.

Thanks.
Jul 18 '05 #8

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

Similar topics

1
by: i_hate | last post by:
Hello, I've just discovered the hard way that classes declaring private variables (beginning with two underscore) can not be pickled ; double underscored attributes are just not returned by...
2
by: Ewald R. de Wit | last post by:
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...
1
by: Venkat Chellam | last post by:
I am new to XML using .net. i have a simple question I have a datatable with oracle. I need to get the data from the table and return the data in form of XML but XML has some schema. I have ..XSD...
4
by: dan.j.weber | last post by:
I see some programs declaring the names of class variables in "__slots__". I've looked this up and the docs say something about old and new style classes, whatever that means. Can someone give me a...
5
by: fortepianissimo | last post by:
I remember from painful experience that copy.copy() won't really copy __slots__ members. But I have trouble explaning why the following code works: --- START--- #!/usr/bin/env python import...
2
by: Pierre Couderc | last post by:
Generally, is there somewhere a good tutorial and examplefor the use of SGI STL hash_set? I am lost in SGI documentation. More specifically, i am trying to use hat I need that a hash_set : ...
3
donilourdu
by: donilourdu | last post by:
hi all, I need sample code for convertion images to pdf format in vb.net.Also tell the free dll file for that . Looking for favor.......... with regards, Doni Agna Lourdu.M
27
by: Licheng Fang | last post by:
Python is supposed to be readable, but after programming in Python for a while I find my Python programs can be more obfuscated than their C/C ++ counterparts sometimes. Part of the reason is that...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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...
0
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...
0
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,...
0
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...

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.