delattr()
delattr(object, name) Returns:
None · Updated March 13, 2026 · Built-in Functions attributes built-in object dynamic
The delattr() built-in function removes a named attribute from an object. It is the programmatic equivalent of the del statement for object attributes. The function takes an object and a string naming the attribute to delete, then removes that attribute if it exists.
Syntax
delattr(object, name)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
object | object | Required | The object from which to delete the attribute. |
name | str | Required | A string specifying the name of the attribute to remove. |
Examples
Basic usage
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
# Delete an attribute
delattr(person, "age")
# This will raise AttributeError
print(person.age)
# AttributeError: 'Person' object has no attribute 'age'
Using with dynamic attribute names
class Config:
def __init__(self):
self.debug = True
self.host = "localhost"
self.port = 8080
config = Config()
# Delete based on user input or variable
attr_to_remove = "port"
if hasattr(config, attr_to_remove):
delattr(config, attr_to_remove)
print(hasattr(config, "port")) # False
Common Patterns
Cleaning up object state
class Session:
def __init__(self, user_id):
self.user_id = user_id
self.authenticated = True
def logout(self):
delattr(self, "authenticated")
# Session is now effectively logged out
session = Session("user123")
session.logout()
print(hasattr(session, "authenticated")) # False
Conditional attribute removal
class Widget:
def __init__(self):
self.visible = True
self.enabled = True
widget = Widget()
# Only delete if attribute exists and meets condition
for attr in ["visible", "enabled", "optional_attr"]:
if hasattr(widget, attr):
value = getattr(widget, attr)
if not value:
delattr(widget, attr)
# Results in widget having no attributes
Resetting object to default state
class GameState:
def __init__(self):
self.score = 0
self.level = 1
self.lives = 3
def full_reset(self):
attrs_to_remove = ["score", "level", "lives"]
for attr in attrs_to_remove:
if hasattr(self, attr):
delattr(self, attr)
game = GameState()
game.score = 100
game.level = 5
game.full_reset()
print(vars(game)) # {}
Errors
AttributeError
delattr(object, "nonexistent")
# AttributeError: 'object' object has no attribute 'nonexistent'
This error occurs when trying to delete an attribute that does not exist. Use hasattr() to check before deleting, or handle the exception:
try:
delattr(obj, "missing_attr")
except AttributeError:
print("Attribute does not exist")
TypeError
delattr(obj, 123)
# TypeError: delattr(): argument 2 must be string, not int
The second argument must be a string. Passing a non-string will raise TypeError.
See Also
- built-in::setattr - Set a named attribute on an object
- built-in::getattr - Get the value of a named attribute
- built-in::hasattr - Check if an object has a named attribute