Python delattr() Function: Remove Object Attributes

When I build small automation scripts, I often create objects to hold temporary report data—such as a customer’s draft notes, an API token, or a calculated status. Once that information is no longer valid, I do not want it sitting on the object and getting reused accidentally.

That is where the Python delattr() function helps. It removes an attribute from an object when you know the attribute name at runtime, which is especially useful in configurable scripts, data-processing jobs, and class-based applications.

In this guide, you will learn the delattr() syntax, see practical examples with complete code and output, and understand when to use it instead of del.

What Is the Python delattr() Function?

The delattr() function is a built-in Python function that deletes a named attribute from an object.

An attribute is a value attached to an object. For example, an employee object may have attributes such as name, department, and access_code.

Here is the syntax:

delattr(object, attribute_name)

The function takes two arguments:

  • object is the class instance or object that contains the attribute
  • attribute_name is a string containing the attribute name you want to remove

Unlike the del object.attribute statement, delattr() works well when the attribute name comes from a variable, user setting, configuration file, or API response.

Python includes many useful built-in tools for everyday scripts. You can also explore other common options in this guide to Python built-in functions.

Python delattr() Function Syntax

The basic syntax looks like this:

delattr(object_name, "attribute_name")

The attribute name must be a string. Python locates that attribute on the object and removes it.

For example, imagine a small customer-reporting script. The script creates a Customer object and later removes the temporary discount_code after the report finishes.

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


customer = Customer("Emma Carter", "Austin", "FALL25")

print("Before deletion:")
print(customer.__dict__)

delattr(customer, "discount_code")

print("\nAfter deletion:")
print(customer.__dict__)

Output:

Before deletion:
{'name': 'Emma Carter', 'city': 'Austin', 'discount_code': 'FALL25'}

After deletion:
{'name': 'Emma Carter', 'city': 'Austin'}

You can see the output in the screenshot below.

Python delattr() Function

The __dict__ attribute stores an object’s writable attributes in a dictionary. It gives you an easy way to confirm what delattr() removed.

This approach works with normal Python classes. If you are still getting comfortable with object-oriented programming, start with the basics of creating a constructor in Python.

How to Use Python delattr() Step by Step

Let’s use one consistent example: a local sales-report automation script. The script creates employee report objects, adds temporary values during processing, and removes those values before saving the final result.

Create an Object with Attributes

First, create a class that represents a sales representative. A class is a blueprint for creating objects, while an object is one usable item created from that blueprint.

class SalesRepresentative:
def __init__(self, name, territory, monthly_sales):
self.name = name
self.territory = territory
self.monthly_sales = monthly_sales


representative = SalesRepresentative(
"Michael Thompson",
"California",
84500
)

print(representative.__dict__)

Output:

{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500}

You can see the output in the screenshot below.

delattr() Function Python

Each self.attribute_name line creates an instance attribute. An instance attribute belongs to one specific object.

For a deeper explanation of how these values differ from class-level values, see class variables vs instance variables in Python.

Delete One Attribute with delattr()

Suppose your report script adds a temporary review_status field. After a manager approves the report, you can delete that temporary value.

class SalesRepresentative:
def __init__(self, name, territory, monthly_sales):
self.name = name
self.territory = territory
self.monthly_sales = monthly_sales


representative = SalesRepresentative(
"Michael Thompson",
"California",
84500
)

representative.review_status = "Pending manager review"

print("Before deleting review_status:")
print(representative.__dict__)

delattr(representative, "review_status")

print("\nAfter deleting review_status:")
print(representative.__dict__)

Output:

Before deleting review_status:
{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500, 'review_status': 'Pending manager review'}

After deleting review_status:
{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500}

You can see the output in the screenshot below.

delattr() Function in Python

The line below does the actual work:

delattr(representative, "review_status")

Python finds the review_status attribute on representative and deletes it. If you try to read it after deletion, Python raises an AttributeError, which means the requested attribute does not exist.

Pro Tip: I have found that temporary attributes work well in small automation scripts, but I always remove them before serializing objects or sending data to another system. That prevents internal processing values from leaking into a report, JSON file, or API payload.

Use delattr() with a Dynamic Attribute Name

The biggest reason to use delattr() instead of del is that the attribute name can come from a variable.

For example, a report-cleanup script might receive a list of fields to remove from a configuration setting. The script does not know the exact attribute until runtime.

class SalesRepresentative:
def __init__(self, name, territory, monthly_sales):
self.name = name
self.territory = territory
self.monthly_sales = monthly_sales
self.internal_note = "Needs follow-up next quarter"


representative = SalesRepresentative(
"Michael Thompson",
"California",
84500
)

attribute_to_remove = "internal_note"

print("Before deletion:")
print(representative.__dict__)

delattr(representative, attribute_to_remove)

print("\nAfter deletion:")
print(representative.__dict__)

Output:

Before deletion:
{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500, 'internal_note': 'Needs follow-up next quarter'}

After deletion:
{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500}

You cannot write this with normal dot notation:

# This removes an attribute literally named attribute_to_remove.
del representative.attribute_to_remove

That line looks for an attribute called attribute_to_remove, not the attribute name stored inside the variable. delattr() solves that problem because it accepts the attribute name as a string.

Dynamic attribute access often appears alongside getattr() and setattr(). You can learn how those functions work together in this guide to dynamic attribute creation with getattr() and setattr().

Check an Attribute Before Calling delattr()

If the attribute does not exist, delattr() raises an AttributeError. In a one-off script, that error may be useful because it exposes a coding mistake. In a scheduled automation script, you may want to handle it cleanly instead.

Use the built-in hasattr() function to check whether an object has an attribute before deleting it.

class SalesRepresentative:
def __init__(self, name, territory, monthly_sales):
self.name = name
self.territory = territory
self.monthly_sales = monthly_sales


representative = SalesRepresentative(
"Michael Thompson",
"California",
84500
)

attribute_to_remove = "review_status"

if hasattr(representative, attribute_to_remove):
delattr(representative, attribute_to_remove)
print(f"Removed: {attribute_to_remove}")
else:
print(f"Nothing removed. '{attribute_to_remove}' does not exist.")

print(representative.__dict__)

Output:

Nothing removed. 'review_status' does not exist.
{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500}

This pattern makes cleanup code safe to run more than once. That matters in scheduled jobs where the same report may rerun after an interruption.

You can also handle the error directly with try and except.

class SalesRepresentative:
def __init__(self, name, territory, monthly_sales):
self.name = name
self.territory = territory
self.monthly_sales = monthly_sales


representative = SalesRepresentative(
"Michael Thompson",
"California",
84500
)

attribute_to_remove = "review_status"

try:
delattr(representative, attribute_to_remove)
print(f"Removed: {attribute_to_remove}")
except AttributeError:
print(f"Cannot remove '{attribute_to_remove}' because it does not exist.")

print(representative.__dict__)

Output:

Cannot remove 'review_status' because it does not exist.
{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500}

Use hasattr() when you expect an attribute may not exist. Use try and except when deletion is part of a larger operation that may fail for more than one reason. If you need more practice with this topic, see how to catch multiple exceptions in Python.

Remove Multiple Attributes with delattr()

A practical cleanup script often removes more than one temporary attribute. Store the names in a list and loop through them.

class SalesRepresentative:
def __init__(self, name, territory, monthly_sales):
self.name = name
self.territory = territory
self.monthly_sales = monthly_sales
self.internal_note = "Strong lead pipeline"
self.review_status = "Approved"
self.export_batch = "BATCH-2026-09"


representative = SalesRepresentative(
"Michael Thompson",
"California",
84500
)

attributes_to_remove = [
"internal_note",
"review_status",
"export_batch"
]

print("Before cleanup:")
print(representative.__dict__)

for attribute_name in attributes_to_remove:
if hasattr(representative, attribute_name):
delattr(representative, attribute_name)

print("\nAfter cleanup:")
print(representative.__dict__)

Output:

Before cleanup:
{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500, 'internal_note': 'Strong lead pipeline', 'review_status': 'Approved', 'export_batch': 'BATCH-2026-09'}

After cleanup:
{'name': 'Michael Thompson', 'territory': 'California', 'monthly_sales': 84500}

This code keeps the important report fields and removes internal fields before export. The hasattr() check makes the loop resilient if one item does not exist.

For a refresher on looping through lists in Python, read how to filter lists in Python.

delattr() vs del in Python

Both delattr() and del can delete an object attribute. The right choice depends on whether you know the attribute name when writing the code.

SituationUse delattr()Use del
Attribute name comes from a variableYesNo
Attribute name is fixed in your source codeYesYes
You need concise code for one known attributeNoYes
You process fields from a configuration fileYesNo
You build a generic cleanup functionYesNo

Here is the same deletion written both ways:

class Report:
def __init__(self):
self.title = "West Coast Sales Report"
self.draft_note = "Check totals before sending"


report = Report()

del report.draft_note

print(report.__dict__)

Output:

{'title': 'West Coast Sales Report'}

Here is the dynamic version:

class Report:
def __init__(self):
self.title = "West Coast Sales Report"
self.draft_note = "Check totals before sending"


report = Report()

field_name = "draft_note"

delattr(report, field_name)

print(report.__dict__)

Output:

{'title': 'West Coast Sales Report'}

Use del report.draft_note when the attribute is fixed and obvious. Use delattr(report, field_name) when your script receives the name dynamically.

Delete Properties with delattr()

A property is a class feature that lets you control attribute access with methods while using normal attribute syntax. A property can include a deleter method that decides what should happen when you call delattr().

This pattern helps when deleting an attribute requires validation, logging, or cleanup work.

class SalesReport:
def __init__(self, report_name, api_token):
self.report_name = report_name
self._api_token = api_token

@property
def api_token(self):
return self._api_token

@api_token.deleter
def api_token(self):
print("Removing the API token from memory.")
del self._api_token


report = SalesReport(
"September Sales Report",
"demo-token-123"
)

print("Token before deletion:", report.api_token)

delattr(report, "api_token")

print("Does _api_token still exist?", hasattr(report, "_api_token"))

Output:

Token before deletion: demo-token-123
Removing the API token from memory.
Does _api_token still exist? False

When Python runs delattr(report, "api_token"), it triggers the property deleter. That gives your class a controlled place to define removal behavior.

Properties are useful when an attribute needs rules rather than plain storage. Read more in this guide to the Python property decorator.

Things to Keep in Mind

  • Use a string name: The second delattr() argument must be a string, such as "internal_note", not an unquoted variable name.
  • Check for missing attributes: Use hasattr() or handle AttributeError when the attribute might not exist.
  • Avoid deleting core data: Do not remove required attributes such as name or id unless your class design expects that change.
  • Treat dynamic names carefully: Validate attribute names that come from users, configuration files, or API data before deleting them.
  • Know that deletion changes the object: After delattr() runs, code that reads that attribute will fail until you create it again.
  • Use properties for controlled cleanup: Add a property deleter when removal should clear related data, write a log message, or enforce business rules.

Frequently Asked Questions

What does delattr() do in Python?

The Python delattr() function removes a named attribute from an object. You provide the object and the attribute name as a string. Python raises an AttributeError if that attribute does not exist.

What is the syntax of delattr() in Python?

Use this syntax:
delattr(object, “attribute_name”)
The first argument is the object. The second argument is a string containing the name of the attribute to delete.

What is the difference between delattr() and del in Python?

Use delattr() when the attribute name comes from a variable or other dynamic source. Use del when you know the attribute name directly in your code, such as del employee.email.

Does delattr() return a value?

No. The delattr() function returns None. Its purpose is to modify the object by removing the specified attribute.

Does delattr() work with class attributes?

It can, but you need to understand where the attribute lives. If an instance inherits an attribute from a class, deleting it from the instance may raise an AttributeError because the instance does not own that attribute. Delete class attributes from the class itself when that is your intended design.

How do I avoid AttributeError with delattr()?

Check first with hasattr(object, "attribute_name"), then call delattr() only when the attribute exists. You can also wrap the call in a try and except AttributeError block when appropriate.

The Python delattr() function gives you a clean way to remove object attributes, especially when your script receives attribute names dynamically. Start with a simple class and a known attribute, then add validation and property-based cleanup as your automation scripts grow. I hope this practical guide helps you use delattr() with confidence.

You May Also Like