How can I call multiple methods/attributes from a package/module simultaneously using a list

Viewed 31

I have a list of attributes present in a module that I want to call one by one using that list. I want to iterate over the names of the attributes stored in the list and call them on the module and store the result in one place.

Here's the code:

CONTOUR_LIST = ["FACEMESH_LIPS", "FACEMESH_FACE_OVAL", "FACEMESH_LEFT_IRIS", "FACEMESH_LEFT_EYEBROW",
           "FACEMESH_LEFT_EYE", "FACEMESH_RIGHT_IRIS", "FACEMESH_RIGHT_EYEBROW", "FACEMESH_RIGHT_EYE"]

This is the module from which I want to use those attributes by iterating over their names from the list. I am trying to subscript the COUNTOUR_LIST on the mp_face_mesh module like this and it's obviously giving me an error. I don't know how to achieve this. Any help would be great.

for i in CONTOUR_LIST:
    for src_id, tar_id in mp_face_mesh.CONTOUR_LIST[i]:
        source = landmarks.landmark[src_id]
        target = landmarks.landmark[tar_id]

        relative_source = int(source.x * img.shape[1]), int(source.y * img.shape[0])
        relative_target = int(target.x * img.shape[1]), int(target.y * img.shape[0])

        cv2.line(img, relative_source, relative_target, 
                color=(255,255,255), thickness=2)
1 Answers

You can use the built-in function getattr:

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.

for attribute in CONTOUR_LIST:
    for src_id, tar_id in getattr(mp_face_mesh, attribute):
        source = landmarks.landmark[src_id]
        target = landmarks.landmark[tar_id]

        relative_source = int(source.x * img.shape[1]), int(source.y * img.shape[0])
        relative_target = int(target.x * img.shape[1]), int(target.y * img.shape[0])

        cv2.line(img, relative_source, relative_target, 
                color=(255,255,255), thickness=2)
Related