473,666 Members | 2,640 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
directly.

Can anyone enlighten me?

Jp

--
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 1892
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
dictoffset).
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.

HTH,
Martin

Jul 18 '05 #2

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

Similar topics

1
1989
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...
9
3077
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
5
2928
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...
3
1634
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.
7
1661
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)...
2
4970
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 ):
4
1490
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.
3
1615
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:...
27
1728
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 *...
0
8363
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
8883
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
8787
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
8561
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
8645
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7389
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...
0
4200
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...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1778
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 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.