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 defined1class Config:2 debug = True3 port = 80804 # Instances can read the class attributes5config = Config()# Attribute names held as strings, decided at runtime6attrs = ["debug", "port", "host"]7for attr in attrs: # Look up the attribute by name; "Not set" is returned instead of AttributeError8 value = getattr(config, attr, "Not set") # Prints debug: True, port: 8080, host: Not set9 print(f"{attr}: {value}")Output
debug: True port: 8080 host: Not set
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