getattr(), setattr(), hasattr()
These three functions read, write and check an attribute using its name as a string.
Used in 19 lessons of the course, from 01.01.
Normally you write obj.name, and the attribute name is fixed in the code. With these functions the name is a string, so it can come from a variable or a loop.
hasattr(obj, "x")returnsTrueifobjhas the attributex, andFalseif not.getattr(obj, "x")returns the value. With a third argument,getattr(obj, "x", default), it returns that default instead of failing.setattr(obj, "x", value)is the same asobj.x = value.
They are written this way because the name is data, not a fixed part of the code. In lesson 01.01 the course uses hasattr(ChatGroq, name) inside a dict comprehension to ask, for each name in a list, whether the class offers that method.
hasattr("hello", "upper") # True
Reach for it when: the attribute name lives in a variable, or when you want to know whether an object has something before using it.
Examples
Common mistake
class Model:
name = "demo"
m = Model()
print(getattr(m, "temperature"))Why: Without a default, getattr fails just like `m.temperature` when the attribute doesn't exist.
How to write it: Pass a third argument: getattr(m, "temperature", None), or check first with hasattr.
Common mistake
class Model:
name = "demo"
m = Model()
print(hasattr(m, name))Why: The attribute name must be a string. Without quotes, Python looks for a variable called name.
How to write it: Put the name in quotes: hasattr(m, "name").
