Python setattr

Summary: in this tutorial, you will learn how to use the Python setattr() function to set a value to an attribute of an object.

Introduction to the Python setattr() function

The setattr() function sets a value to an attribute specified by the string name of an object. The following shows the syntax of the setattr() function:

setattr(object, name, value)Code language: Python (python)

The setattr() function has the following parameters:

  • object is the object that you want to set the attribute.
  • name is the name of the attribute that you want to set a value.
  • value is the value to set.

In practice, you’ll use the setattr() function in metal programming. Please check out the Meta class and its example for the practical usage of the setattr() function.

Python setattr() function examples

Let’s take some examples of using the setattr() function.

1) Using Python setattr() to set a value to an attribute of an object

The following example defines a Person class and uses the setattr() to assign a value to the age attribute:

class Person:
    def __init__(self, name):
        self.name = name


person = Person('John')
setattr(person, 'age', 22)

print(person.__dict__)Code language: Python (python)

Output:

{'name': 'John', 'age': 22}Code language: Python (python)

In this example, the Person class doesn’t have the age attribute. The setattr() adds the age attribute to the person object and sets its values to 22.

Note that the setattr() only changes an individual person object, not the Person class. If you create another instance of the Person class, this object won’t have the age attribute. For example:

class Person:
    def __init__(self, name):
        self.name = name


person = Person('John')
setattr(person, 'age', 22)
print(person.__dict__)  # {'name': 'John', 'age': 22}

person2 = Person('Jane')
print(person2.__dict__)  # {'name': 'Jane'}Code language: Python (python)

2) Using Python setattr() to assign a method to an object

The following example uses the setattr() function to assign a function to an object:

class Person:
    def __init__(self, name):
        self.name = name


def say_hi():
    return 'Hi'


person = Person('John')
setattr(person, 'greeting', say_hi)
print(person.greeting())Code language: Python (python)

How it works.

First, define a Person class:

class Person:
    def __init__(self, name):
        self.name = nameCode language: Python (python)

Second, define the say_hi() function:

def say_hi():
    return 'Hi'Code language: Python (python)

Third, create a new Person object and assign the say_hi function to the greeting attribute of the person object:

person = Person('John')
setattr(person, 'greeting', say_hi)Code language: Python (python)

Finally, call the say_hi() function via the greeting() attribute:

print(person.greeting())Code language: Python (python)

Output:

HiCode language: Python (python)

Using setattr() to convert a dictionary to an object

When you work with a dictionary, especially one that has a lot of nested dictionaries, you need to use square brackets with keys surrounded by a string. For example:

person_dict = {
    'first_name': 'John',
    'last_name': 'Doe',
    'skills': ['Python', 'Tkinter', 'Django'],
    'address': {
        'house_no': 999,
        'street': 'Fox Avenue',
        'city': 'San Jose',
        'state': 'CA',
        'zipcode': 95134,
        'country': 'USA'
    }
}Code language: Python (python)

To get the value of first name of the person_dict dictionary, you need to use the 'first_name' string as a key:

person_dict['first_name']Code language: Python (python)

To get the value of the state of the person_dict, you need to access the address first and then use the 'state' string as a key:

person_dict['address']['state']Code language: CSS (css)

It would be more convenient to access the state like an object like this:

person_dict.address.stateCode language: Python (python)

To do that, you need to convert the dictionary to an object. The key of each key/value pair in the dictionary is the attribute of the object. Also, you need to deal with the nested dictionaries.

The following DictToObject class uses the setattr() function and recursive technique to convert a dictionary to an object:

class DictToObject:
    def __init__(self, d):
        if not isinstance(d, dict):
            raise ValueError('The argument d must be a dictionary object')

        for key, value in d.items():
            if isinstance(value, (list, tuple)):
                setattr(self, key, [DictToObject(v) if isinstance(v, dict)
                                    else v for v in value])
            else:
                setattr(self, key, DictToObject(value)
                        if isinstance(value, dict) else value)
Code language: Python (python)

The following shows how to convert the person_dict to the person object using the DictToObject class:

class DictToObject:
    def __init__(self, d):
        if not isinstance(d, dict):
            raise ValueError('The argument d must be a dictionary object')

        for key, value in d.items():
            if isinstance(value, (list, tuple)):
                setattr(self, key, [DictToObject(v) if isinstance(v, dict)
                                    else v for v in value])
            else:
                setattr(self, key, DictToObject(value)
                        if isinstance(value, dict) else value)


if __name__ == '__main__':
    person_dict = {
        'first_name': 'John',
        'last_name': 'Doe',
        'skills': ['Python', 'Tkinter', 'Django'],
        'address': {
            'house_no': 999,
            'street': 'Fox Avenue',
            'city': 'San Jose',
            'state': 'CA',
            'zipcode': 95134,
            'country': 'USA'
        }
    }

    person = DictToObject(person_dict)
    print(person.first_name)  # John
    print(person.address.state)  # CACode language: Python (python)

Summary

  • Use Python setattr() function to set a value to an attribute of an object.
Did you find this tutorial helpful ?