Lookup object attribute via variable?

In python, I need to write a method that searches through a list of objects based on it's attribute. The object has 10 attributes, so rather than either writing 10 lookup methods or a series of IF - ELIF, I'd like to do something like this:

def lookup(list, attribute, value):
    for object in list:
        if object.attribute == value:
            return object

Is there a way to do this in python, or any other language? I feel like this is a feature that I've always wanted but never see.

Posted Jul 4, 2020, 8:46 PM UTC

11
marko312•

If you really want to do this, there is a function called getattr which can do this in Python. Documentation

attr = getattr(object, attribute)

If this is to interface with some not-too-well written module, this is probably an acceptable solution. However, otherwise (especially if it's your own code), I'd consider changing the classes to be accessible by such keys.

2