hasattr
, getattr
and setattr
are 3 powerful features in python which helps you to write reflective programs. Reflection is the ability of a computer program to examine and modify its own properties at runtime.
hasattr
hasattr
helps us to check whether an attribute is present in an object. If the object has the given attribute, hasattr
will return True
. Otherwise, it will return False
. Theoretically, this gives a program the ability to examine its own properties (Self-awareness?).
list_obj = [1, 2, 3]
hasattr(list_obj, 'append') # Returns True
tuple_obj = (1, 2, 3)
hasattr(tuple_obj, 'append') # Returns False
In the above program, we have two objects. The first one is a list
and the second one is a tuple
. We are trying to check whether the object has an append
method in it. This is one way of differentiating between a tuple and list(You should use isinstance
for this - something is possible does not mean it is correct).
getattr
getattr
is used to retrieve a value from an object, if you have the attribute name as a string object. The usual way of accessing attribute values in python is obj.attribute_name
. But what if the attribute name is not known at the time of writing the program? Imagine a situation like the following example.
attr_name = 'my_unknown_attribute'
Here you have attribute name stored in a variable as a string object. So how can we access my_unknown_attribute
using attr_name
string variable? Pretty simple. Right? You just have to do
attr_name = 'my_unknown_attribute'
my_obj.attr_name
You may have figured out that this is not going to work. It will give you the value of the attr_name
property, not the value of my_unknown_attribute
property. The built-in getattr
function comes handy in these cases.
getattr
function takes two arguments: any type of python object (which includes everything in python) as the first argument and a string object as the second argument. getattr
will return the value of the attribute which is given as the string argument.
Using getattr
, our unknown attribute problem can be solved as follows.
attr_name = 'my_unknown_attribute'
attr_value = getattr(my_obj, attr_name)
There is still a problem. What if the object does not has an attribute in the given name? Python will raise an AttributeError
and your program will break. In real programs, you will be using getattr
for string names that are available at run time. These string names can come from a variety of sources such as user input from a website, a file in file system etc. In these cases, you may need to avoid breaking your program. So you should add an exception handling block.
attr_name = 'my_unknown_attribute'
try:
attr_value = getattr(my_obj, attr_name)
except AttributeError:
attr_value = 'Somebody cheated. No value for this name'
This code is perfectly alright except that there is a much easier way in python. getattr
takes a third argument, which will act as a default value in case of an AttributeError
. So we can rewrite our program as
attr_name = 'my_unknown_attribute'
attr_value = getattr(my_obj, attr_name, 'Somebody cheated. No value for this name')
Filling the default value with a complaint may not very useful in real programs. You may want to use None
or False
instead of saying somebody cheated you.
setattr
By now you may have guessed the purpose of setattr
function. As you have imagined, it is used to set the value for an attribute, whose name is stored in a string object. So in our my_unknown_attribute
example, if you want to set a value for the attribute, you should do the following.
attr_name = 'my_unknown_attribute'
setattr(my_obj, attr_name, 'my_value')
setattr
takes 3 parameters and all 3 are required. First one is the object to which the value has to be set, the second one is the name of the attribute, and the third one is the value to set. The value need not be a string. It can be any python object.