In this tutorial, you’ll learn about the Python setattr() function, including what it does, when to use it, and when it’s redundant to use it. The function is used to set an attribute to a value of an object, whether the attribute exists or not.
By the end of this tutorial, you’ll have learned:
- What the Python
setattr()
function does and how to use it - When the function will fail and how to prevent this error
- Why the function can be redundant for setting an attribute
- How the function can be used to add set multiple object attributes at once
Table of Contents
Understanding the Python setattr Function
The Python setattr function is used to set the value of an attribute of an object. The function can be used to:
- Set the attribute of an existing attribute, or
- Create a new attribute and set it to a provided value
Let’s take a look at what this function looks like:
# Understanding the Python setattr() Function
setattr(
object, # The object to set the attribute on
name, # The name of the attribute
value # The value of the attribute
)
We can see that the function takes three parameters: the object itself, the name of the attribute, and the value to be set.
Using setattr to Set an Attribute that Exists
Let’s take a look at how we can use the function to set an attribute’s value:
# Setting the attribute of an object
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
Nik = Employee("Nik", 75000)
print('Before changing attribute...')
print('Nik.salary:', Nik.salary)
setattr(Nik, "salary", 80000)
print('After changing attribute...')
print('Nik.salary:', Nik.salary)
# Returns:
# Before changing attribute...
# Nik.salary: 75000
# After changing attribute...
# Nik.salary: 80000
Let’s break down what the code above does:
- We first create a class,
Employee
, which has two attributes,name
andsalary
- We then instantiate a new Employee object and set two initial attributes
- When then use the
setattr()
function to modify thesalary
attribute
Using setattr to Set an Attribute that Doesn’t Exist
In the example above, we used the setattr()
function to modify the value of an attribute that already exists. However, we can also use it to set an attribute that doesn’t yet exist. Let’s add an attribute using the setattr()
function to the same class:
# Setting the attribute of an object when the attribute doesn't exist
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
Nik = Employee("Nik", 75000)
setattr(Nik, "location", "Toronto")
print('Nik.location:', Nik.location)
# Returns:
# Nik.location: Toronto
We can see that the function works in setting an attribute’s value, even if that attribute didn’t previously exist.
Why Python setattr May Be Redundant
The Python setattr()
function works in setting attributes in Python objects. However, it may also be redundant since there are much simpler and, arguably, more Pythonic ways of accomplishing the same thing. We can use dot notation to do this.
Let’s recreate the example above using dot notation:
# Using other methods to set attributes
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
Nik = Employee("Nik", 75000)
Nik.salary = 80000
Nik.location = 'Toronto'
print("Nik.salary:", Nik.salary)
print("Nik.location:", Nik.location)
We can see that both of these methods worked to set attributes easily. There are some perks to using the setattr()
function, however – read on to learn more.
How to Set Multiple Object Attributes in Python with setattr
One of the perks of using the setattr()
function is to be able to set multiple attributes at once. Imagine that you’re provided with a dictionary of attributes belonging to an object. You can loop over these and set them for the different attributes of an object.
Let’s see what this looks like:
# Setting multiple attributes with Python setattr()
class Employee:
def __init__(self, name):
self.name = name
Nik = Employee("Nik")
attributes = {
'Age': 33,
'Location': 'Toronto',
'Salary': 75000
}
for attribute, value in attributes.items():
setattr(Nik, attribute, value)
print(vars(Nik))
# Returns: {'name': 'Nik', 'Age': 33, 'Location': 'Toronto', 'Salary': 75000}
In the example above, we loop over each key and value in the dictionary. We then use the setattr()
function to add these attributes and values. Finally, we use the vars()
function to print out a dictionary that contains the object’s attributes.
When setattr Will Fail and How to Resolve Errors
The Python setattr()
function will fail if it’s used on objects that don’t yet exist. This means that an object needs to first be instantiated in order to prevent any errors. Because of this, the function can’t be used to instantiate an object, but rather only work with ones that already exist.
# setattr() Will Fail When an Object Doesn't Exist
class Employee:
def __init__(self, name):
self.name = name
setattr(Nik, "age", 30)
# Returns: NameError: name 'Nik' is not defined
In order to resolve this, we first need to create the object:
# Resolving the NameError Raised by setattr()
class Employee:
def __init__(self, name):
self.name = name
Nik = Employee("Nik")
setattr(Nik, "age", 30)
Conclusion
In this tutorial, you learned how to use the Python setattr()
function to set the attribute of an object to a value. You first learned how the function is defined and how to use it for both attributes that already exist and for ones that don’t. You then learned why the function can be redundant since you can simply use dot notation.
Then, you learned how to use the function to set multiple attributes using a for loop as well as how to resolve errors that may occur when using the function.
Additional Resources
To learn more about related topics, check out the tutorials below: