Python del statement, delattr() function With Examples

Python del statement and delattr() function is used to delete the attribute of an object. Both of them does the exact same thing. However, delattr() function is useful when we want to delete an attribute dynamically, for example deleting attribute of an object based on user input.

Python del statement

Let’s say we have Employee class defined as:


class Employee:
    id = -1
    name=""
    def __init__(self, i, n, r):
        self.id = i
        self.name = n
        self.role = r
    def __str__(self):
        return "Employee[id={}, name={}, role={}]".format(self.id, self.name, self.role)

Notice that id and name are class variables whereas the role is instance variable.

Let’s see some example of using del statement to delete class attributes.


e = Employee(10, 'Pankaj', 'CEO')
print(e)
print(e.id)
print(e.name)
print(e.role)
# del with class attribute
del e.id
print(e)
print(e.id)
del e.name
print(e.name)

Output:


Employee[id=10, name=Pankaj, role=CEO]
10
Pankaj
CEO
Employee[id=-1, name=Pankaj, role=CEO]
-1

So when we deleted class variable using del statement, in further access default value is returned.

Now let’s see what happens when we try to delete the instance variable and then access it.


del e.role
print(e.role)

Output:


AttributeError: 'Employee' object has no attribute 'role'

So when instance attribute is deleted, future access to them is causing AttributeError.

Python delattr()

Python delattr() syntax is:


delattr(object, name)

The first argument is the object whose attribute we want to delete. The second argument is the name of the attribute we want to delete from the object.

Let’s look at some delattr() function examples.


e = Employee(10, 'Pankaj', 'CEO')
print(e)
print(e.id)
print(e.name)
print(e.role)
delattr(e, 'id')
print(e)
print(e.id)
delattr(e, 'name')
print(e.name)

Output:


Employee[id=10, name=Pankaj, role=CEO]
10
Pankaj
CEO
Employee[id=-1, name=Pankaj, role=CEO]
-1

Let’s see what happens when we try to delete the instance variable ‘role’.


delattr(e, 'role')
print(e.role)

Output:


AttributeError: 'Employee' object has no attribute 'role'

Python del vs delattr()

It’s clear from the above examples that del statement and delattr() function does the same thing. So when to use del statement and when to go for delattr() function?

If you are deleting an object attribute statically in the program, it makes sense to use del statement. However, delattr() function is the only way when you want to dynamically assign the attribute to delete. For example, taking user input to delete an object attribute. Let’s see this with a simple example.


# delattr() benefit with dynamic attribute deletion
e = Employee(20, 'Lisa', 'Editor')
print(e)
attr = input('Please enter attribute to delete, valid values are id, name and rolen')
delattr(e, attr)
print(e)

Output:


Employee[id=20, name=Lisa, role=Editor]
Please enter attribute to delete, valid values are id, name and role
id
Employee[id=-1, name=Lisa, role=Editor]

Note that I am deleting the class variable. Below image shows the output when we are trying to delete instance variable and later our program is trying to access it.

python-del-delattr


Employee[id=20, name=Lisa, role=Editor]
Please enter attribute to delete, valid values are id, name and role
role
Traceback (most recent call last):
  File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_del_delattr_examples.py", line 47, in
    print(e)
  File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_del_delattr_examples.py", line 11, in __str__
    return "Employee[id={}, name={}, role={}]".format(self.id, self.name, self.role)
AttributeError: 'Employee' object has no attribute 'role'

Python delete attribute vs setting to None

If you want to reuse the attribute, you can set it to None. However, if you delete the instance attribute then you will get an error in accessing it unless you set it again.


# set to None vs del/delattr
e.role = None
print('Role=", e.role)
del e.role
e.role = "CEO'
print('Role=", e.role)

Output:


Role = None
Role = CEO

Deleting already deleted attribute

If we try to delete an already deleted attribute, we will get AttributeError.


e = Employee(20, "Lisa', 'Editor')
del e.id
# del e.id # AttributeError: id
delattr(e, 'name')
# delattr(e, 'name')  # AttributeError: name

Deleting Non Existing Attribute

If we try to delete an object attribute that doesn’t exist, we will get AttributeError.


# del e.x  # AttributeError: x
# delattr(e, 'x')  # AttributeError: x

That’s all for python del statement and delattr() function.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: