Int and float different behavior with TypeError "object layout differs from"

Minimal repro to illustrate my question:

results in TypeError: __class__ assignment: 'B' object layout differs from 'A'

The very same code for float won’t throw any error:

I also found out that if I add __slots__ = () attribute to both A and B definitions no errors will appear in the __class__ reassignment.

Is this different behavior for int and float an expected one?

P.S. Real code is in the autoreload extension for jupyter, where it tries to reload the changed class and if it’s a child of int it throws this error.

Python version 3.10.8.

Related Topics

Why does the `'Mesh' object layout differ from` `mesh.create_unit_square`?

I am trying to follow the tutorial of DOLFINx , but when I got to

A [0,1]\times[0,1] mesh distributed among processes

, it showed the message

How do I solve it? Thanks.

These may be related

https://github.com/FEniCS/dolfinx/issues/2423 https://github.com/FEniCS/dolfinx/pull/2500 https://github.com/FEniCS/dolfinx/issues/2519

:slight_smile:

Python 3.11 support was added after the 0.6.0 release. To use dolfinx with Python 3.11 you need to work on the main branch.

I appreciate the effort (see the solution below)

Related Topics

  • Create Account

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

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.

  • Python Home
  • Documentation
  • Developer's Guide
  • Random Issue
  • Issues with patch
  • Easy issues

Google

  • Lost your login?
  • Committer List
  • Tracker Documentation
  • Tracker Development
  • Report Tracker Problem

typeerror __class__ assignment object layout differs from

This issue tracker has been migrated to GitHub , and is currently read-only . For more information, see the GitHub FAQs in the Python's Developer Guide.

This issue has been migrated to GitHub: https://github.com/python/cpython/issues/79229

Created on 2018-10-23 10:07 by bup , last changed 2022-04-11 14:59 by admin .

Extending the tf.Tensor class

I want to extend the tf.Tensor class, but neither of the following options work. I do want to specifically extend it though, and not store a tf.tensor instance as an attribute in my own class!

  • option: extend tf.Tensor:

Fails with:

  • Option: extend EagerTensor

Does anyone have a solution for this?

Hi @anon25443

Welcome to the TensorFlow Forum!

You can not subclass tf.tensor which also causes the above error. This is not recommended and often not feasible due to internal complexities within TensorFlow.

Inheriting directly from EagerTensor is not allowed because it’s not designed to be a base class for user-defined extensions. Thank you.

• Home Page •

The Decorator Pattern ¶

A “Structural Pattern” from the Gang of Four book

The “Decorator Pattern” ≠ Python “decorators”!

If you are interested in Python decorators like @classmethod and @contextmanager and @wraps() , then stay tuned for a later phase of this project in which I start tackling Python language features.

The Decorator Pattern can be useful in Python code! Happily, the pattern can be easier to implement in a dynamic language like Python than in the static languages where it was first practiced. Use it on the rare occasion when you need to adjust the behavior of an object that you can’t subclass but can only wrap at runtime.

  • Implementing: Static wrapper
  • Implementing: Tactical wrapper
  • Implementing: Dynamic wrapper
  • Caveat: Wrapping doesn’t actually work
  • Hack: Monkey-patch each object
  • Hack: Monkey-patch the class
  • Further Reading

The Python core developers made the terminology surrounding this design pattern more confusing than necessary by using the decorator for an entirely unrelated language feature . The timeline:

  • The design pattern was developed and named in the early 1990s by participants in the “Architecture Handbook” series of workshops that were kicked off at OOPSLA ’90, a conference for researchers of object-oriented programming languages.
  • The design pattern became famous as the “Decorator Pattern” with the 1994 publication of the Gang of Four’s Design Patterns book.
  • In 2003, the Python core developers decided to re-use the term decorator for a completely unrelated feature they were adding to Python 2.4.

Why were the Python core developers not more concerned about the name collision? It may simply be that Python’s dynamic features kept its programming community so separate from the world of design-pattern literature for heavyweight languages that the core developers never imagined that confusion could arise.

To try to keep the two concepts straight, I will use the term decorator class instead of just decorator when referring to a class that implements the Decorator Pattern.

Definition ¶

A decorator class:

  • Is an adapter (see the Adapter Pattern )
  • That implements the same interface as the object it wraps
  • That delegates method calls to the object it wraps

The decorator class’s purpose is to add to, remove from, or adjust the behaviors that the wrapped object would normally implement when its methods are called. With a decorator class, you might:

  • Log method calls that would normally work silently
  • Perform extra setup or cleanup around a method
  • Pre-process method arguments
  • Post-process return values
  • Forbid actions that the wrapped object would normally allow

These purposes might remind you of situations in which you would also think of subclassing an existing class. But the Decorator Pattern has a crucial advantage over a subclass: you can only solve a problem with a subclass when your own code is in charge of creating the objects in the first place. For example, it isn’t helpful to subclass the Python file object if a library you’re using is returning normal file objects and you have no way to intercept their construction — your new MyEvenBetterFile subclass would sit unused. A decorator class does not have that limitation. It can be wrapped around a plain old file object any time you want, without the need for you be in control when the wrapped object was created.

Implementing: Static wrapper ¶

First, let’s learn the drudgery of creating the kind of decorator class you would write in C++ or Java. We will not take advantage of the fact that Python is a dynamic language, but will instead write static (non-dynamic) code where every method and attribute appears literally, on the page.

To be complete — to provide a real guarantee that every method called and attribute manipulated on the decorator object will be backed by the real behavior of the adapted object — the decorator class will need to implement:

  • Every method of the adapted class
  • A getter for every attribute
  • A setter for every attribute
  • A deleter for every attribute

This approach is conceptually simple but, wow, it involves a lot of code!

Imagine that one library is giving you open Python file objects, and you need to pass them to another routine or library — but to debug some product issues with latency, you want to log each time that data is written to the file.

Python file objects often seem quite simple. We usually read() from them, write() to them, and not much else. But in fact the file object supports more than a dozen methods and offers five different attributes! A wrapper class that really wants to implement that full behavior runs to nearly 100 lines of code — as shown here, in our first working example of the Decorator Pattern:

So for the sake of the half-dozen lines of code at the bottom that supplement the behavior of write() and writelines() , another hundred or so lines of code wound up being necessary.

You will notice that each Python object attribute goads us into being even more verbose than Java! A typical Java attribute is implemented as exactly two methods, like getEncoding() and setEncoding() . A Python attribute, on the other hand, will in the general case need to be backed by three actions — get, set, and delete — because Python’s object model is dynamic and supports the idea that an attribute might disappear from an instance.

Of course, if the class you are decorating does not have as many methods and attributes as the Python file object we took as our example, then your wrapper will be shorter. But in the general case, writing out a full wrapper class will be tedious unless you have a tool like an IDE that can automate the process. Also, the wrapper will need to be updated in the future if the underlying object gains (or loses) any methods, arguments, or attributes.

Implementing: Tactical wrapper ¶

The wrapper in the previous section might have struck you as ridiculous. It tackled the Python file object as a general example of a class that needed to be wrapped, instead of studying the how file objects work to look for shortcuts:

  • File objects are implemented in the C language and don’t, in fact, permit deletion of any of their attributes. So our wrapper could have omitted all 6 deleter methods without any consequence, since the default behavior of a property in the absence of a deleter is to disallow deletion anyway. This would have saved 18 lines of code.
  • All file attributes except mode are read-only and raise an AttributeError if assigned to — which is the behavior if a property lacks a setter method. So 5 of our 6 setters can be omitted, saving 15 more lines of code and bringing our wrapper to ⅓ its original length without sacrificing correctness.

It might also have occurred to you that the code to which you are passing the wrapper is unlikely to call every single file method that exists. What if it only calls two methods? Or only one? In many cases a programmer has found that a trivial wrapper like the following will perfectly satisfy real-world code that just wants to write to a file:

Yes, this can admittedly be a bit dangerous. A routine that seems so happy with a minimal wrapper like this can suddenly fail later if rare circumstances make it dig into methods or attributes that you never implemented because you never saw it use them. Even if you audit the library’s code and are sure it can never call any method besides write() , that could change the next time you upgrade the library to a new version.

In a more formal programming language, a duck typing requirement like “this function requires a file object” would likely be replaced with an exact specification like “this argument needs to support a writelines() method” or “pass an object that offers every methods in the interface IWritableFile .” But most Python code lacks this precision and will force you, as the author of a wrapper class, to decide where to draw the line between the magnificent pedantry of wrapping every possible method and the danger of not wrapping enough.

Implementing: Dynamic wrapper ¶

A very common approach to the Decorator Pattern in Python is the dynamic wrapper. Instead of trying to implement a method and property for every method and attribute on the wrapped object, a dynamic wrapper intercepts live attribute accesses as the program executes and responds by trying to access the same attribute on the wrapped object.

A dynamic wrapper implements the dunder methods __getattr__() , __setattr__() , and — if it really wants to be feature-complete — __delattr__() and responds to each of them by performing the equivalent operation on the wrapped object. Because __getattr__() is only invoked for attributes that are in fact missing on the wrapper, the wrapper is free to offer real implementations of any methods or properties it wants to intercept.

There are a few edge cases that prevent every attribute access from being handled with __getattr__() . For example, if the wrapped object is iterable, then the basic operation iter() will fail on the wrapper if the wrapper is not given a real __iter__() method of its own. Similarly, even if the wrapped object is an iterator, next() will fail unless the wrapper offers a real __next__() , because these two operations examine an object’s class for dunder methods instead of hitting the object directly with a __getattr__() .

As a result of these special cases, a getattr-powered wrapper usually involves at least a half-dozen methods in addition to the methods you specifically want to specialize:

As you can see, the code can be quite economical compared to the vast slate of methods we saw earlier in WriteLoggingFile1 for manually implementing every possible attribute.

This extra level of indirection does carry a small performance penalty for every attribute access, but is usually preferred to the burden of writing a static wrapper.

Dynamic wrappers also offer pleasant insulation against changes that might happen in the future to the object being wrapped. If a future version of Python adds or removes an attribute or method from the file object, the code of WriteLoggingFile3 will require no change at all.

Caveat: Wrapping doesn’t actually work ¶

If Python didn’t support introspection — if the only operation you could perform on an object was attribute lookup, whether statically through an identifier like f.write or dynamically via getattr(f, attrname) string lookup — then a decorator could be foolproof. As long as every attribute lookup that succeeds on the wrapped object will return the same sort of value when performed on the wrapper, then other Python code would never know the difference.

But Python is not merely a dynamic programming language; it also supports introspection. And introspection is the downfall of the Decorator Pattern. If the code to which you pass the wrapper decides to look deeper, all kinds of differences become apparent. The native file object, for example, is buttressed with many private methods and attributes:

Your wrapper, on the other hand — if you have crafted it around the file’s public interface — will lack all of those private accouterments. Behind your carefully implemented public methods and attributes are the bare dunder methods of a generic Python object , plus the few you had to implement to maintain compatibility:

The tactical wrapper, of course, looks spectacularly different than a real file object, because it does not even attempt to provide the full range of methods available on the wrapped object:

More interesting is the getattr wrapper. Even though, in practice, it offers access to every attribute and method of the wrapped class, they are completely missing from its dir() because each attribute only springs into existence when accessed by name.

Could even these differences be ironed out? If you scroll through the many dunder methods in the Python Data Model , your might be struck by a sudden wild hope when you see the __dir__ method — surely this is the final secret to camouflaging your wrapper?

Alas, it will not be enough. Even if you implement __dir__() and forward it through to the wrapped object, Python special-cases the __dict__ attribute — accessing it always provides direct access to the dictionary that holds a Python class instance’s attributes.

You might begin to think of even more obscure ways to subvert Python’s introspection — at this point you might already be thinking of __slots__ , for example — but all roads lead to the same place. However clever and obscure your maneuvers, at least a small chink will still be left in your wrapper’s armor which will allow careful enough introspection to see the difference. Thus we are lead to a conclusion:

The Decorator Pattern in Python supports programming — but not metaprogramming . Code that is happy to simply access attributes will be happy to accept a Decorator Pattern wrapper instead. But code that indulges in introspection will see the difference.

Among other things, Python code that attempts to list an object’s attributes, examine its __class__ , or directly access its __dict__ will see differences between the object it expected and the decorator object you have in fact given it instead. Well-written application code would never do such things, of course — they are necessary only when implementing a developer tool like a framework, test harness, or debugger. But as you don’t always have the option of dealing solely with well-written libraries, be prepared to see and work around any symptoms of intrusive introspection as you deploy the Decorator Pattern.

Hack: Monkey-patch each object ¶

There are two final approaches to decoration based on the questionable practice of monkey patching. The first approach takes each object that needs decoration and installs a new method directly on the object, shadowing the official method that remains on the class itself.

If you have ever attempted this maneuver yourself, you might have run aground on the fact that a function installed on a Python object instance does not receive an automatic self argument — instead, it sees only the arguments with which it is literally invoked. So a first try at supplementing a file’s write() with logging:

— will die with an error because the new method sees only one argument, not two:

The quick way to resolve the dilemma is to do the binding yourself, by providing the object instance to the closure that wraps the new method itself:

While clunky, this approach does let you update the action of a single method on a single object instance while leaving the entire rest of its behavior alone.

Hack: Monkey-patch the class ¶

Another approach you might see in the wild is to create a subclass that has the desired behaviors overridden, and then to surgically change the class of the object instance. This is not, alas, possible in the general case, and in fact fails for our example here because the file class, like all built-in classes, does not permit assignment to its __class__ attribute:

But in cases where the surgery does work, you will have an object whose behavior is that of your subclass rather than of its original class.

Further Reading ¶

  • If dynamic wrappers and monkey patching spur your interest, check out Graham Dumpleton’s wrapt library , his accompanying series of blog posts , and his monkey patching talk at Kiwi PyCon that delve deep into the arcane technical details of the practice.

© 2018–2020  Brandon Rhodes

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Panic when setting __class__ with different layout #4634

@qingshi163

qingshi163 commented Mar 5, 2023

@qingshi163

youknowone commented Mar 5, 2023

Sorry, something went wrong.

No branches or pull requests

@youknowone

IMAGES

  1. How to Fix Uncaught TypeError: Assignment to constant variable.

    typeerror __class__ assignment object layout differs from

  2. vue3.2关于“TypeError: Assignment to constant variable”的问题解决方案

    typeerror __class__ assignment object layout differs from

  3. vue3.2关于“TypeError: Assignment to constant variable”的问题解决方案_assignment

    typeerror __class__ assignment object layout differs from

  4. TypeError: Assignment to constant variable

    typeerror __class__ assignment object layout differs from

  5. TypeError: 'str' Object Does Not Support Item Assignment

    typeerror __class__ assignment object layout differs from

  6. How to Fix "TypeError 'int' object does not support item assignment

    typeerror __class__ assignment object layout differs from

VIDEO

  1. haiiiii everyone!!! Gresiana Herauwani's English assignment "Object Description"

  2. #TypeError: 'int' object is not iterable#how to add one int value inside tuple?

  3. Oracle Reports 12c in Hindi: Repeating Frames, Group Left/Above, Confine Mode, Flex Mode, Data Model

  4. The ultimate SHORTCUT for PowerPoint!

  5. CS Foundations

  6. MCS 219 Solved Assignment// MCA_NEW 2nd Semester #solvedassignments #ignousolvedassignment #MCA_NEW

COMMENTS

  1. class design

    can somebody describe the following exception? What is the "object layout" and how it is defined? Thanks Traceback (most recent call last): File "test_gui.py", line 5, in <module> suit...

  2. Int and float different behavior with TypeError "object layout differs

    Bug report Next code: class A(int): pass class B(int): pass a = A(1) a.__class__ = B Results in TypeError: __class__ assignment: 'B' object layout differs from 'A' The very same code for float won't throw any error: class C(float): pass ...

  3. Int and float different behavior with TypeError "object layout differs

    Minimal repro to illustrate my question: class A(int): pass class B(int): pass a = A(1) a.__class__ = B results in TypeError: __class__ assignment: 'B' object layout differs from 'A' The very same code for float won't throw any error: class C(float): pass class D(float): pass c = C(1.2) c.__class__ = D I also found out that if I add __slots__ = () attribute to both A and B definitions no ...

  4. autoreload gratuitous "object layout differs" error #13347

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  5. Issue 4600: __class__ assignment error message confusing

    Note: Even when type(ob) and someclass both 'qualify', the assignment will fail if instances are 'incompatible'. Let M be a subclass of types.ModuleType. c.__class__ = M # fails with TypeError: __class__ assignment: 'M' object layout differs from 'C' The difference is obvious by looking as dir(c) and dir(M('somename')).

  6. TypeError: __class__ assignment: 'KernelWithCustomEnqueue' object

    TypeError: __class__ assignment: 'KernelWithCustomEnqueue' object layout differs from 'pyopencl._cl.Kernel' #661 Closed anbe42 opened this issue Nov 19, 2022 · 2 comments

  7. Why does the `'Mesh' object layout differ from` `mesh.create_unit

    Hello, I am trying to follow the tutorial of DOLFINx, but when I got to. A [0,1]\times[0,1] mesh distributed among processes. from mpi4py import MPI from dolfinx import mesh domain = mesh.create_unit_square( MPI.COMM_WORLD, 8, 8, mesh.CellType.quadrilateral)

  8. assigning to __class__ for an extension type: Is it still possible

    TypeError: __class__ assignment: '_PClass' deallocator differs from 'PClass' ... TypeError: __class__ assignment: '_PClass' object layout differs from 'PClass' It seems thus that this approach is not possible, but problem is that delegation ( embedding a _PClass instance in PClass (lets say as _base attribute) and automatically forwarding all

  9. Issue 35048: Can't reassign __class__ despite the assigned class having

    The relevant logic is in the compatible_for_assignment() function on line 3972 in Objects/typeobject.c. After checking that the tp_free slots are the same, it proceeds as follows: /* It's tricky to tell if two arbitrary types are sufficiently compatible as to be interchangeable; e.g., even if they have the same tp_basicsize, they might have ...

  10. __class__ assignment error message confusing #48850

    terryjreedy commented on Dec 8, 2008. to join this conversation on GitHub . Already have an account? BPO 4600 Nosy @terryjreedy, @benjaminp, @aroberge, @merwok, @Trundle, @jonashaag, @florentx, @iritkatriel Files 4600.diff Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current sta...

  11. difference 2.3 versus 2.2

    TypeError: __class__ assignment: 'float' object layout differs from 'int' In 2.3, this rules was tightened that not only the layout must be compatible, but both old and new type must be "heap types", i.e. created through a class statement.

  12. Extending the tf.Tensor class

    Hey there! I want to extend the tf.Tensor class, but neither of the following options work. I do want to specifically extend it though, and not store a tf.tensor instance as an attribute in my own class!. option: extend tf.Tensor: class MyTFTensor(tf.Tensor): @classmethod def _from_native(cls, value: tf.Tensor): value.__class__ = cls return value y = MyTFTensor._from_native(value=tf.zeros((3 ...

  13. TypeError: __class__ assignment: 'FLARE_Atoms' object layout differs

    TypeError: __class__ assignment: 'FLARE_Atoms' object layout differs from 'Atom' #325. Closed lenardcarroll opened this issue Oct 23, 2022 · 3 comments ... "TypeError: class assignment: 'FLARE_Atoms' object layout differs from 'Atom'" Not sure how to fix this or how to go forward with it. Some help would be appreciated.

  14. The Decorator Pattern

    Definition¶. A decorator class:. Is an adapter (see the Adapter Pattern); That implements the same interface as the object it wraps; That delegates method calls to the object it wraps; The decorator class's purpose is to add to, remove from, or adjust the behaviors that the wrapped object would normally implement when its methods are called.

  15. python

    Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

  16. difference 2.3 versus 2.2

    >TypeError: __class__ assignment: 'float' object layout differs from 'int' > >In 2.3, this rules was tightened that not only the layout must be >compatible, but both old and new type must be "heap types", i.e. created >through a class statement.

  17. Assignment to __bases__ of direct object subclasses #37817

    On 4th line, the variable named "A" is bound to a new type object. This type has no attribute by itself. The first dir (A) displays the attributes of the bases class, which are. the previous A and B: you see ['one', 'two'] The second dir (A) displays the attributes of the bases class, which. are B and C: you see ['two', 'three']

  18. Python: How to rebase or dynamically replace a class with a different

    Ui = r"C:\pythonTest\ui\test.ui" app = PySideGui.QApplication (sys.argv) win = MyGui (Ui) That's what I was trying to do, but as a decorator. You don't want a decorator, since you don't want to edit an existing class; you want to define the class with the correct base in the first place. The difference is decorator (Class (FixedBase)) (changing ...

  19. Panic when setting __class__ with different layout #4634

    Summary Setting object's class attribute to a type with different layout cause panic thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 0', vm/src/obj... Skip to content Toggle navigation