Python delattr() Function: Syntax and 5 Examples

If you want to delete an object’s attribute in Python, the Python delattr function is what you’re looking for. It takes the object and the attribute name as a string and removes it, like del obj.name.

delattr(user, "phone")   # same as: del user.phone
print(hasattr(user, "phone"))   # False

In this tutorial, I’ll take delattr() from a basic delete to string names, class attributes and a custom guard, all run on Python 3.12.5 in VS Code.

Python delattr() Syntax

delattr(object, name, /)
ParameterRequiredDefaultDescription
objectYesnoneThe object, class or module to change
nameYesnoneThe attribute name as a string

Return value: None. A missing attribute raises AttributeError.

Note: delattr() is one of the Python built-in functions, so there’s nothing to import.

When to Use delattr() in Python

  • The attribute name comes from a variable or config file
  • Stripping sensitive fields before logging an object
  • Resetting an instance to the class default
  • Cleaning up attributes added with setattr()

For the other half of the toolkit, read my getattr(), setattr() and hasattr() tutorial.

Example 1: Delete an Attribute from an Object in Python

Let me start with a simple customer object:

class Customer:
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone

c = Customer("Megan Ross", "512-555-0147")
print(delattr(c, "phone"))
print(vars(c))
print(hasattr(c, "phone"))

Output:

None
{'name': 'Megan Ross'}
False
Python delattr function deleting the phone attribute from a Customer object in VS Code
delattr() returns None.

How does this work? delattr() returned None and removed phone, so hasattr() gives False.

vars() reads the object’s __dict__ attribute in Python.

Example 2: Use delattr() with an Attribute Name Stored in a String

Here, I’ll drop payment fields before logging an order:

class Order:
    def __init__(self):
        self.total = 249.99
        self.card_token = "tok_9f3a"
        self.billing_zip = "60614"

order = Order()
for field in ["card_token", "billing_zip"]:
    delattr(order, field)

print("Safe to log:", vars(order))

Output:

Safe to log: {'total': 249.99}
Python delattr removing card_token and billing_zip from an Order object in a loop in VS Code
Names come from a list.

How does this work? The loop passed each name as a string. del order.field fails here, because Python looks for an attribute literally called field. That’s the delattr() vs del difference.

Example 3: Check with hasattr() Before Calling delattr()

A helper keeps a missing attribute from crashing your Python script:

class Invoice:
    def __init__(self):
        self.amount = 845.25
        self.discount = 50.00

def remove_attr(obj, name):
    if hasattr(obj, name):
        delattr(obj, name)
        return True
    return False

inv = Invoice()
print(remove_attr(inv, "discount"))
print(remove_attr(inv, "discount"))

Output:

True
False

How does this work? The first call deleted discount. The second returned False instead of raising an error.

Pro Tip: a try/except AttributeError block works too. See how to catch multiple exceptions in Python.

Example 4: Delete a Class Attribute in Python with delattr()

Instance and class attributes behave differently:

class Shipment:
    rate = 7.99

box = Shipment()
box.rate = 0.00
delattr(box, "rate")
print("After delattr(box):", box.rate)

delattr(Shipment, "rate")
print(hasattr(box, "rate"))

Output:

After delattr(box): 7.99
False
Python delattr on an instance attribute falling back to the class attribute, then deleting the class attribute
Instance first, then the class.

How does this work? Deleting box.rate removed only the instance override, so 7.99 came back. delattr(Shipment, "rate") removed it for every instance.

More on this in class vs instance variables in Python.

Example 5: Block Deletion with a Custom __delattr__() Method

Every delattr() call goes through __delattr__(), so you can protect fields:

class Account:
    def __init__(self):
        self.acct_id = "AC-7781"
        self.nickname = "Vacation fund"

    def __delattr__(self, name):
        if name == "acct_id":
            raise AttributeError("acct_id is protected")
        super().__delattr__(name)

acct = Account()
delattr(acct, "nickname")
print(vars(acct))
try:
    delattr(acct, "acct_id")
except AttributeError as err:
    print("AttributeError:", err)

Output:

{'acct_id': 'AC-7781'}
AttributeError: acct_id is protected
Python delattr calling a custom __delattr__ method that blocks deleting acct_id
__delattr__() runs on every delete.

How does this work? nickname was deleted. For acct_id, our method raised AttributeError first.

A property with a deleter is another way to control this.

Common Mistakes with Python delattr()

These are the Python errors you’ll see most (more in types of errors in Python):

class Car:
    def __init__(self):
        self.make = "Ford"
        self.__vin = "1FTFW1E5"

car = Car()
tests = ['delattr(car, "model")', 'delattr(car, 5)',
         'delattr(car)', 'delattr("Ford", "upper")',
         'delattr(car, "__vin")']
for expr in tests:
    try:
        eval(expr)
    except (AttributeError, TypeError) as err:
        print(f"{type(err).__name__}: {err}")

delattr(car, "_Car__vin")
print(vars(car))

Output:

AttributeError: 'Car' object has no attribute 'model'
TypeError: attribute name must be string, not 'int'
TypeError: delattr expected 2 arguments, got 1
AttributeError: 'str' object attribute 'upper' is read-only
AttributeError: 'Car' object has no attribute '__vin'
{'make': 'Ford'}
Common Python delattr mistakes: AttributeError for missing and read-only attributes, TypeError for non-string names
Real delattr() errors.
  1. The attribute doesn’t exist.
  2. The name isn’t a string.
  3. The second argument is missing.
  4. Built-in types like str are read-only.
  5. Private names need the mangled _Car__vin.

Wrapping Up the Python delattr() Function

Python’s delattr() deletes an attribute by name and returns None. Use it when the name is a string; otherwise del reads better.

Next, browse more Python built-in functions and methods.

If you work with objects a lot, these pair well with delattr():

Questions About Python delattr() Function

What does delattr do in Python?

It deletes one attribute from an object by name.

Does delattr() return anything?

No. It always returns None.

Can delattr() delete a method?

Only from the class, like delattr(MyClass, "save").

Can I use delattr() on a dictionary key?

No. Dictionary keys aren’t attributes. See how to remove a dictionary key.

Does the name have to be a valid identifier?

No. Any string works, such as "first name" set with setattr(). See delattr() in the Python docs.