Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/hl7/accessor.py : 34%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# -*- coding: utf-8 -*-
2from __future__ import unicode_literals
3from collections import namedtuple
4import six
5from .compat import python_2_unicode_compatible
8@python_2_unicode_compatible
9class Accessor(namedtuple('Accessor', ['segment', 'segment_num', 'field_num', 'repeat_num', 'component_num', 'subcomponent_num'])):
10 __slots__ = ()
12 def __new__(cls, segment, segment_num=1, field_num=None, repeat_num=None, component_num=None, subcomponent_num=None):
13 """Create a new instance of Accessor for *segment*. Index numbers start from 1."""
14 return super(Accessor, cls).__new__(cls, segment, segment_num, field_num, repeat_num, component_num, subcomponent_num)
16 @property
17 def key(self):
18 """Return the string accessor key that represents this instance"""
19 seg = self.segment if self.segment_num == 1 else self.segment + six.text_type(self.segment_num)
20 return ".".join(six.text_type(f) for f in [seg, self.field_num, self.repeat_num, self.component_num, self.subcomponent_num] if f is not None)
22 def __str__(self):
23 return self.key
25 @classmethod
26 def parse_key(cls, key):
27 """Create an Accessor by parsing an accessor key.
29 The key is defined as:
31 | SEG[n]-Fn-Rn-Cn-Sn
32 | F Field
33 | R Repeat
34 | C Component
35 | S Sub-Component
36 |
37 | *Indexing is from 1 for compatibility with HL7 spec numbering.*
39 Example:
41 | PID.F1.R1.C2.S2 or PID.1.1.2.2
42 |
43 | PID (default to first PID segment, counting from 1)
44 | F1 (first after segment id, HL7 Spec numbering)
45 | R1 (repeat counting from 1)
46 | C2 (component 2 counting from 1)
47 | S2 (component 2 counting from 1)
48 """
49 def parse_part(keyparts, index, prefix):
50 if len(keyparts) > index:
51 num = keyparts[index]
52 if num[0].upper() == prefix:
53 num = num[1:]
54 return int(num)
55 else:
56 return None
58 parts = key.split('.')
59 segment = parts[0][:3]
60 if len(parts[0]) > 3:
61 segment_num = int(parts[0][3:])
62 else:
63 segment_num = 1
64 field_num = parse_part(parts, 1, 'F')
65 repeat_num = parse_part(parts, 2, 'R')
66 component_num = parse_part(parts, 3, 'C')
67 subcomponent_num = parse_part(parts, 4, 'S')
68 return cls(segment, segment_num, field_num, repeat_num, component_num, subcomponent_num)