How to called Class instance from given string variable in Python


This is pretty interesting. You have give string list like “InsuranceUser”, “InsuranceUserProfile”, etc. That are string. Now, you should called class that have name same with the given string. I will show in Django models as more real explanation.

To fetch InsuranceUser models, usually we do :

1
2
3
from insurance.models import InsuranceUser

user_list = InsuranceUser.objects.all()


Given some string :

1
some_string = "InsuranceUser"

Now, we can use getattr(), which is explain as :

getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Then we can easily get object by modules name. Examples :

1
2
import insurance.models
insurance_model =  getattr(insurance.models, ‘InsuranceUser’)

Now “insurance_model” assigned as InsuranceUser class instance. You can call any method inside this class. For instance:

1
2
3
import insurance.models
insurances =  getattr(insurance.models, ‘InsuranceUser’)
insurances.objects.get(id=12)

It will throw result :

1
<InsuranceUser: InsuranceUser object>

getattr() is powerfull command in Python which we can call attributes from given objects (Class, Modules, etc).


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.