Deleting existing class variable yield AttributeError

2024/9/30 9:30:13

I am manipulating the creation of classes via Python's metaclasses. However, although a class has a attribute thanks to its parent, I can not delete it.

class Meta(type):def __init__(cls, name, bases, dct):super().__init__(name, bases, dct)if hasattr(cls, "x"):print(cls.__name__, "has x, deleting")delattr(cls, "x")else:print(cls.__name__, "has no x, creating")cls.x = 13
class A(metaclass=Meta):pass
class B(A):pass

The execution of the above code yield an AttributeError when class B is created:

A has no x, creating
B has x, deleting
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-49e93612dcb8> in <module>()10 class A(metaclass=Meta):11     pass
---> 12 class B(A):13     pass14 class C(B):<ipython-input-3-49e93612dcb8> in __init__(cls, name, bases, dct)4         if hasattr(cls, "x"):5             print(cls.__name__, "has x, deleting")
----> 6             delattr(cls, "x")7         else:8             print(cls.__name__, "has no x, creating")AttributeError: x

Why can't I delete the existing attribute?

EDIT: I think my question is different to delattr on class instance produces unexpected AttributeError which tries to delete a class variable via the instance. In contrast, I try to delete a class variable (alias instance) via the class (alias instance). Thus, the given fix does NOT work in this case.

EDIT2: olinox14 is right, it's an issue of "delete attribute of parent class". The problem can be reduced to:

class A:x = 13
class B(A):pass
del B.x
Answer

It seems like python register the x variable as a paramameter of the A class:

capture

Then, when you try to delete it from the B class, there is some conflict with the delattr method, like mentionned in the link that @David Herring provided...

A workaround could be deleting the parameter from the A class explicitly:

delattr(A, "x")
https://en.xdnf.cn/q/71095.html

Related Q&A

Setting global font size in kivy

What is the preferred way, whether through python or the kivy language, to set the global font size (i.e. for Buttons and Labels) in kivy? What is a good way to dynamically change the global font size…

What is the difference between load name and load global in python bytecode?

load name takes its argument and pushes onto the stack the value of the name stored by store name at the position indicated by the argument . load global does something similar, but there appears to …

porting Python 2 program to Python 3, random line generator

I have a random line generator program written in Python2, but I need to port it to Python3. You give the program the option -n [number] and a file argument to tell it to randomly output [number] numbe…

Symbol not found, Expected in: flat namespace

I have a huge gl.pxd file with all the definitions of gl.h, glu.h and glut.h. For example it has these lines:cdef extern from <OpenGL/gl.h>:ctypedef unsigned int GLenumcdef void glBegin( GLenum m…

Why does Django not generate CSRF or Session Cookies behind a Varnish Proxy?

Running Django 1.2.5 on a Linux server with Apache2 and for some reason Django seems like it cannot store CSRF or Session cookies. Therefore when I try to login to the Django admin it gives me a CSRF v…

Shared state with aiohttp web server

My aiohttp webserver uses a global variable that changes over time:from aiohttp import web shared_item = blaasync def handle(request):if items[test] == val:shared_item = doedaprint(shared_item)app =…

ModuleNotFoundError: No module named matplotlib.pyplot

When making a plot, I used both Jupyter Notebook and Pycharm with the same set of code and packages. The code is: import pandas as pd import numpy as np import matplotlib.pyplot as plt # as in Pycha…

python linux - display image with filename as viewer window title

when I display an image with PIL Image it opens an imagemagick window but the title is some gibberish name like tmpWbfj48Bfjf. How do I make the image filename to be the title of the viewer window?

Request body serialization differences when lambda function invoked via API Gateway v Lambda Console

I have a simple API set up in AWS API Gateway. It is set to invoke a Python 2.7 lambda function via API Gateway Proxy integration.I hit a strange error in that the lambda worked (processed the body co…

Determining a homogeneous affine transformation matrix from six points in 3D using Python

I am given the locations of three points:p1 = [1.0, 1.0, 1.0] p2 = [1.0, 2.0, 1.0] p3 = [1.0, 1.0, 2.0]and their transformed counterparts:p1_prime = [2.414213562373094, 5.732050807568877, 0.7320508075…