Skip to content

setattr()

The built-in setattr() function allows you to set the value of an attribute of an object dynamically at runtime using the attribute’s name as a string. This is particularly useful when you don’t know the attribute names in advance:

Language: Python
>>> class Person:
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
...

>>> jane = Person("Jane", 25)
>>> setattr(jane, "age", 26)
>>> jane.age
26

setattr() Signature

Language: Python Syntax
setattr(object, name, value)

Arguments

Argument Description
object The object whose attribute you want to set.
name A string representing the name of the attribute to set.
value The new value you want to assign to the specified attribute.

Return Value

  • The setattr() function doesn’t return a fruitful value. Instead, it modifies the input object by setting the specified attribute to the given value.

setattr() Examples

With a class instance as an argument:

Language: Python
>>> class Car:
...     def __init__(self, make, model):
...         self.make = make
...         self.model = model
...

>>> toyota = Car("Toyota", "Corolla")
>>> setattr(toyota, "year", 2020)
>>> toyota.year
2020

setattr() Common Use Cases

The most common use cases for setattr() include:

  • Dynamically setting attributes when the attribute names are determined at runtime
  • Modifying attributes of objects in a generic way, such as within a loop
  • Implementing frameworks or libraries that require flexible attribute management

setattr() Real-World Example

Suppose you have a scenario where you need to update multiple attributes of an object based on a dictionary of key-value pairs. You can use setattr() to achieve this dynamically.

Language: Python
>>> class Book:
...     def __init__(self, title, author, year):
...         self.title = title
...         self.author = author
...         self.year = year
...

>>> book = Book("1984", "George Orwell", 1949)
>>> updates = {"title": "Animal Farm", "year": 1945}
>>> for attr, value in updates.items():
...     setattr(book, attr, value)
...
>>> book.title
'Animal Farm'
>>> book.year
1945

In this example, setattr() helps update the book object’s attributes based on the provided dictionary, allowing for flexible and dynamic attribute management.

Tutorial

Python Built-in Functions: A Complete Guide

Use Python's built-in functions for math, data types, iterables, and I/O to write shorter, more Pythonic code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Feb. 9, 2026 • Reviewed by Dan Bader