Dynamic setattr in Python

Level 4189 keystrokes

This uses setattr() to dynamically add attributes to an object from a dictionary.

Python code

# An empty class; attributes will be added at runtime
1class DynamicObj:
2 pass
3
# Create an instance with no attributes yet
4obj = DynamicObj()
# Attribute names and values to set
5data = {"name": "Alice", "age": 30, "city": "Tokyo"}
6
# Loop over each key-value pair
7for key, value in data.items():
# setattr(obj, key, value) is obj.<key> = value with the name as a string
8 setattr(obj, key, value)
9
# The new attributes work like normal ones: Alice 30 Tokyo
10print(obj.name, obj.age, obj.city)

Output

Alice 30 Tokyo
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 10
  • ,× 7
  • :× 5
  • .× 4
  • (× 4
  • )× 4
  • =× 2
  • {× 1
  • }× 1

More Python examples at level 4

← Python typing practice