Python delattr(): Delete Object Attributes — Syntax, Instance vs Class, Properties and Deleters, __slots__, Errors, Safety, and Practical Examples > dev

Skip to content

Entire search within the site

👈Go back dev

Python Python delattr(): Delete Object Attributes — Syntax, Instance vs Class…

page info

name Goposu datetime⏰ 25-10-11 02:51 hit👁️ 14 comment💬 0

text

최적화된 WebP 이미지

Python delattr(): Remove an attribute from an object

The built-in delattr() function deletes an attribute by name from an object. It mirrors the statement del obj.attr but accepts the attribute name dynamically (at runtime). This guide covers correct usage, differences between instance and class deletion, interaction with properties and descriptors, __slots__, common errors, and safe patterns.

Syntax

delattr(obj, name)

Parameters: obj is any Python object; name is a string naming the attribute to delete.

Behavior: Equivalent to del obj.name. Raises AttributeError if the attribute does not exist or is non-deletable; may raise TypeError for immutable or restricted objects.

Quick examples

class User:
    def __init__(self):
        self.name = "Alice"
        self.age = 30

u = User()
print(u.__dict__)      # {'name': 'Alice', 'age': 30}
delattr(u, "age")
print(hasattr(u, "age"))  # False

# Dynamic attribute deletion
attr = "name"
delattr(u, attr)
print(hasattr(u, "name"))  # False

Instance vs class attributes

Deleting on an instance removes entries from the instance’s __dict__ (or its descriptors). Deleting on the class removes class-level attributes for all instances.

class Config:
    flag = True

c = Config()
print(c.flag)          # True (inherited from class)
delattr(Config, "flag")
# Now c.flag lookup fails
print(hasattr(c, "flag"))  # False

Properties, descriptors, and deleters

If the target is a property or descriptor with a deleter, delattr() will invoke it. Without a deleter, deletion fails with AttributeError.

class Product:
    def __init__(self):
        self._price = 10
    @property
    def price(self): return self._price
    @price.deleter
    def price(self): self._price = None

p = Product()
delattr(p, "price")
print(p._price)        # None

__slots__ and restricted objects

Classes with __slots__ restrict attributes to predefined slots. Deletion works only if the slot’s descriptor supports it; otherwise, an AttributeError is raised. Immutable or frozen types (e.g., frozen dataclasses, namedtuple instances) do not allow attribute deletion.

class Point:
    __slots__ = ("x", "y")
    def __init__(self): self.x, self.y = 1, 2

pt = Point()
delattr(pt, "x")
print(hasattr(pt, "x"))  # False
# delattr(pt, "z")  # AttributeError: 'Point' object has no attribute 'z'

Common pitfalls and errors

  • Non-existent attribute: Raises AttributeError. Check with hasattr() first if unsure.
  • Read-only descriptors: Properties without a deleter or read-only descriptors cannot be deleted.
  • Deleting methods from instances: Methods live on the class; deleting on the instance won’t remove the method. Delete from the class to affect all instances.
  • Built-in/extension types: Many built-ins (e.g., int, str) don’t allow arbitrary attributes; deletion is unsupported.
  • Namespace side effects: delattr() modifies the object’s attribute set in place—be careful in shared or global contexts.
# Guarded deletion
def safe_del(obj, name):
    if hasattr(obj, name):
        delattr(obj, name)

# Deleting a method must target the class
class A:
    def f(self): return 1
delattr(A, "f")
print(hasattr(A(), "f"))  # False

Design and debugging tips

  • Use feature flags: Prefer toggling booleans over deleting attributes for clearer intent.
  • Log deletions: In dynamic systems, log or audit deletions to track state changes.
  • Fail loudly: When deletion is required, let AttributeError bubble up to catch configuration errors early.
# Audited deletion helper
def delete_with_log(obj, name):
    if not hasattr(obj, name):
        raise AttributeError(f"{obj!r} has no attribute {name!r}")
    print(f"Deleting {name} from {type(obj).__name__}")
    delattr(obj, name)

FAQ

Is delattr(obj, name) the same as del obj.name?
Yes. delattr() is the dynamic function form of the del statement.
Can I delete attributes from modules?
Yes, module attributes can be removed, but it may break imports or code relying on them—use with caution.
How do I prevent deletion?
Use properties without a deleter, read-only descriptors, or encapsulate state to avoid external mutation.
Will deleting a class attribute affect existing instances?
Yes. Instances that relied on the class attribute will no longer find it after deletion.

Related keywords

Python delattr, delete attribute, descriptors, property deleter, __slots__, AttributeError, dynamic deletion, class vs instance

👍good0 👎nogood 0

comment list 0

There are no registered comments.

이미지 목록

전체 19건 1 페이지
게시물 검색
Copyright © https://goposu.com All rights reserved.
View PC version