python-3.xhl7-v2

How to dynamic call class instance attribute?


I am doing some parse work with hl7apy parse, and i occurred with one problem.
I use hl7apy to parse hl7 message, which can be parse:

from hl7apy.parser import parse_message
message = "MSH|^~\&|HIS|HIS|MediII|MediII|20170902141711||ORM^O01^ORM_O01|15b 37e7132504a0b95ade4654b596dc5|P|2.4\r"
msg = parse_message(message, find_groups=False)
print(msg.msh.msh_3.msh_3_1.value)

output:

'HIS'

so, how can i get field value dynamically according to field config?
for example, the msh field config :

{
    "field": "msh",
    "field_index": [3,1]
}

so the value can be find with:

msg.msh.msh_3.msh_3_1.value

and if config change to:

{
    "field": "pid",
    "field_index": [2,4]
}

the get field line will be:

msg.pid.pid_2.pid_2_4.value

Solution

  • You could combine a few list comprehensions and use getattr recursively.

    # recursively get the methods from a list of names
    def get_method(method, names):
        if names:
            return get_method(getattr(method, names[0]), names[1:])
        return method
    
    field_config = {
        'field': 'msh',
        'field_index': [3, 1]
    }
    # just get the field
    field = field_config['field']
    # get a list of the indexes as string. ['3', '1']
    indexes = [str(i) for i in field_config['field_index']]
    # join the indexes with a '_' starting with nothing
    # and put it in a list of names. ['msh', 'msh_3', 'msh_3_1']
    names = ['_'.join([field] + indexes[:i]) for i in range(len(indexes) + 1)]
    # get the method from the recursive function
    method = get_method(msg, names)
    print(method.value)
    

    As a disclaimer, I had no way of testing it so it may not work exactly as you expect it. But this should be a good starting point.