pythonobjectscapytlv

Any better code to define generic TLV initiatzed to different types


Maybe more of this is object oriented programming based -

defined a generic TLV as

 class MYTLV(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, defaultTLV_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]

I have many TLV of same form but have different type. How can i have better code to reduce this in codes as

     class newTLV(MYTLV):
          some code to say or initiaze type field of this newTLV to newTLV_enum
     ....

So later I can use as -

     PacketListField('tlvlist', [], newTLV(fields.type=newTLV_enum))

All TLVs are same except for the dictionary for the type field.

    class MYTLV1(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, TLV1_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]
   class MYTLV2(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, TLV2_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]

Solution

  • You could do it like this:

    base_fields_desc = [
        FieldLenField("length", None, fmt='B', length_of="value"),
        StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
    ]
    
    def fields_desc_with_enum_type(enum_type):
        fields_desc = base_fields_desc[:]
        fields_desc.insert(0, ByteEnumField("type", 0x1, enum_type))
        return fields_desc
    
    
    class MYTLV1(Packet):
        fields_desc = fields_desc_with_enum_type(TLV1_enum)
    
    class MYTLV2(Packet):
        fields_desc = fields_desc_with_enum_type(TLV2_enum)