1+ import abc
12from io import BytesIO
23
34from kafka .protocol .abstract import AbstractType
67from kafka .util import WeakMethod
78
89
9- class Struct (AbstractType ):
10- SCHEMA = Schema ()
10+ class Struct (metaclass = abc .ABCMeta ):
11+
12+ @abc .abstractproperty
13+ def SCHEMA (self ):
14+ """An instance of Schema() representing the structure"""
15+ pass
1116
1217 def __init__ (self , * args , ** kwargs ):
13- if len (args ) == len (self .SCHEMA . fields ):
18+ if len (args ) == len (self .SCHEMA ):
1419 for i , name in enumerate (self .SCHEMA .names ):
1520 setattr (self , name , args [i ])
1621 elif len (args ) > 0 :
@@ -23,19 +28,7 @@ def __init__(self, *args, **kwargs):
2328 % (list (self .SCHEMA .names ),
2429 ', ' .join (kwargs .keys ())))
2530
26- # overloading encode() to support both class and instance
27- # Without WeakMethod() this creates circular ref, which
28- # causes instances to "leak" to garbage
29- self .encode = WeakMethod (self ._encode_self )
30-
31- @classmethod
32- def encode (cls , item ): # pylint: disable=E0202
33- bits = []
34- for i , field in enumerate (cls .SCHEMA .fields ):
35- bits .append (field .encode (item [i ]))
36- return b'' .join (bits )
37-
38- def _encode_self (self ):
31+ def encode (self ):
3932 return self .SCHEMA .encode (
4033 [getattr (self , name ) for name in self .SCHEMA .names ]
4134 )
@@ -44,7 +37,7 @@ def _encode_self(self):
4437 def decode (cls , data ):
4538 if isinstance (data , bytes ):
4639 data = BytesIO (data )
47- return cls (* [ field . decode (data ) for field in cls . SCHEMA . fields ] )
40+ return cls (* cls . SCHEMA . decode (data ))
4841
4942 def get_item (self , name ):
5043 if name not in self .SCHEMA .names :
0 commit comments