getattr with Default in Python

Level 4177 keystrokes

This uses getattr() with a default value to safely access object attributes.

Python code

# A class with two class attributes; host is not defined
1class Config:
2 debug = True
3 port = 8080
4
# Instances can read the class attributes
5config = Config()
# Attribute names held as strings, decided at runtime
6attrs = ["debug", "port", "host"]
7for attr in attrs:
# Look up the attribute by name; "Not set" is returned instead of AttributeError
8 value = getattr(config, attr, "Not set")
# Prints debug: True, port: 8080, host: Not set
9 print(f"{attr}: {value}")

Output

debug: True
port: 8080
host: Not set
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
  • =× 5
  • ,× 4
  • :× 3
  • (× 3
  • )× 3
  • {× 2
  • }× 2
  • [× 1
  • ]× 1

More Python examples at level 4

← Python typing practice