Python setattr()

Python’s built-in setattr(object, string, value) function takes three arguments: an object, a string, and an arbitrary value. It sets the attribute given by the string on the object to the specified value. After calling the function, there’s a new or updated attribute at the given instance, named and valued as provided in the arguments. For example, setattr(object, 'attribute', 42) is equivalent to object.attribute = 42.

How to Set an Attribute Dynamically in Python? A visual guide to setattr()

Usage

Learn by example! Here’s an example on how to use the setattr() built-in function.

Create a Car object porsche with a new attribute speed and set it to the value 100:

# Define class with one attribute
class Car:
    None


# Create object
porsche = Car()
setattr(porsche, 'speed', 100)

# What's the value for attribute speed?
print(porsche.speed)
# 100

Video setattr()

Syntax setattr()

The setattr() object has the following syntax:

Syntax: 
setattr(object, attribute, value)         # Set or update object's attribute to value
ArgumentsobjectThe object for which the attribute should be set.
stringThe attribute name to be set or updated.
objectThe value to set the attribute to.
Return ValueNoneReturns Nothing. Just sets or updates the attribute.

Interactive Shell Exercise: Understanding setattr()

Consider the following interactive code:

Exercise: Before you run the code, guess the output!


But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


Practical Application: Python setattr() self

In object-oriented programming, you can often see the use of the setattr() built-in function in combination with the object self in the __init__() constructor method.

The idea is to be able to create a class with dynamic attributes chosen at runtime by the user or the program. This way, you can create container classes that hold arbitrary attributes.

class Person:
    def __init__(self, attributes):
        for key, value in attributes.items():
            setattr(self, key, value)


# Create two different persons
alice = Person({'name': 'Alice', 'income': 180000, 'eyes': 'blue'})
bob = Person({'firstname': 'Max', 'lastname': 'Power'})


# Different persons, different attributes
print(alice.name + ' ' + str(alice.income) + ' ' + alice.eyes)
print(bob.firstname + ' ' + bob.lastname)


# Output:
'''
Alice 180000 blue
Max Power
'''

Note that this is a very convenient way to create classes with different attribute names. However, you should consider whether you can improve your object-oriented modeling because the concept of a class may not be suitable if the instances don’t have the same attributes.

Python setattr() vs assignment

There are two equivalent ways to set or update the value of a new attribute for an object:

  • Use the setattr(object, "attribute", value) function.
  • Use the assignment operation object.attribute = value.

The difference is that the setattr() requires a string value of the attribute name while the assignment operation requires the name of the attribute itself. Thus, if you have only the textual representation of the attribute to be set—for example, from a dictionary of key value pairs—you should use the setattr() function. But if you have the explicit attribute name, it’s often more straightforward and readable to use the assignment.

class Person:
    None


# ASSIGNMENT:
# Create Alice with one attribute name
alice = Person()
alice.name = 'alice'

# SETATTR():
# Create Bob with one attribute name
bob = Person()
setattr(bob, 'name', 'bob')

print(alice.name)
print(bob.name)

'''
alice
bob
'''

Related Functions

  • The getattr() function returns the value of an attribute.
  • The setattr() function changes the value of an attribute.
  • The hasattr() function checks if an attribute exists.
  • The delattr() function deletes an existing attribute.

Summary

Python’s built-in setattr(object, string, value) function takes three arguments: an object, a string, and an arbitrary value.

It sets the attribute given by the string on the object to the specified value. After calling the function, there’s a new or updated attribute at the given instance, named and valued as provided in the arguments.

For example, setattr(object, 'attribute', 42) is equivalent to object.attribute = 42:

class O:
    None
    
obj = O()
setattr(obj, 'attribute', 42)
print(obj.attribute)
# 42

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!