473,729 Members | 2,148 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tp_base, tp_basesize, and __slots__ instance __class__ reassignment

In trying to update some code built on top of reload(), I've hit a point
of confusion in how it is determined whether or not __class__ is allowed to
be rebound.

Consider, for example:
class Foo(object): ... __slots__ = 'a', 'b'
... class Bar(object): ... __slots__ = 'a', 'b'
... f = Foo()
f.__class__ = Bar

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __class__ assignment: 'Bar' object layout differs from 'Foo'

The cause of this particular error does not actually seem to be that the
object layouts of Bar and Foo are incompatible, but rather that the object
layouts of _object_ and Foo are incompatible.

I've tracked down the point of rejection to same_slots_adde d
(Objects/typeobject.c:23 47 or thereabouts):

static int
same_slots_adde d(PyTypeObject *a, PyTypeObject *b)
PyTypeObject *base = a->tp_base;
int size;

if (base != b->tp_base)
return 0;
if (equiv_structs( a, base) && equiv_structs(b , base))
return 1;
size = base->tp_basicsize ;
if (a->tp_dictoffse t == size && b->tp_dictoffse t == size)
size += sizeof(PyObject *);
if (a->tp_weaklistoff set == size && b->tp_weaklistoff set == size)
size += sizeof(PyObject *);
return size == a->tp_basicsize && size == b->tp_basicsize ;

I do not understand why the final line is comparing size against each of a
and b's tp_basicsize, rather than perfoming some comparison between a and b

Can anyone enlighten me?


Where a calculator on the ENIAC is equipped with 18,000 vacuum tubes and
weighs 30 tons, computers in the future may have only 1,000 vacuum tubes and
weigh only 1.5 tons. -- Popular Mechanics, March 1949

Jul 18 '05 #1
1 1896
Jp Calderone wrote:
Can anyone enlighten me?

The test doesn't recognize the addition of arbitrary same slots.
Instead, it only looks for the __dict__ slot and the weakrefs slot.
If any additional slots have been added to either subclass, the
classes are considered different.

To test whether just these two slots have been added in lock-step,
you check
1. the dictoffset is the same for both classes, and it follows
immediately the base slots, or neither class has a dictoffset.
2. the weakrefs offset is the same for both classes, and it follows
immediately the dictoffset (or the base slots if there was no
3. there are no additional slots

Now, this *could* be generalized to treating to classes the same if
they have the same user-defined slots. If you want to do that, looking
at the size is not sufficient - you also have to verify that the slot
names and offsets are the same, lock-step-wise.


Jul 18 '05 #2

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

Similar topics

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 there a container that holds the values of attributes contained in __slots__? In __dict__, you have...
by: flori | last post by:
i try to greate somthing like this class ca(object): __slots__ = ("a",) class cb(ca): __slots__ = ("a","b") class cc(ca): __slots__ = ("a","c") class cd(cb,cc): __slots__ = ("a","b","c","d") but i didn't find a simple solution so i'm using a metaclass that generate a __slots__-free and a __slots__-version
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 in secs, the average size per instance in Bytes and the average CPU time per instance in...
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 hopefully be in a future version of Python.
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 use the instance of OptimizedRectangle, say, x, with 'width' and 'heigth', but (quoting the book)...
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 AttributeError. Is this by design (if so, why)? class A( object ): __slots__ = ( 'value', ) value = 1 def __init__( self, value = None ):
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 simple, brief explanation of what __slots__ are and when I should use them? Thanks.
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 slotted class are read-only irrespective of whether their names are included in __slots__ or not:...
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 with heterogeneous lists/tuples at hand, I tend to stuff many things into the list and *assume* a structure of the list or tuple, instead of declaring them explicitly as one will do with C structs. So, what used to be struct nameval { char *...
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
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,...
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...
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,...
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
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...
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.