<s> from . integer import intX <EOL> def enum ( length , values , default = None ) : <EOL> def make_enum_field ( parent , ** field_options ) : <EOL> enum_field = intX ( length , signed = False ) ( parent , ** field_options ) <EOL> old_encode_fn = enum_field . _encode_fn <EOL> old_decode_fn = enum_field . _decode_fn <EOL> keys = { v : k for k , v in list ( values . items ( ) ) } <EOL> def encode_enum ( key ) : <EOL> if key not in keys : <EOL> raise ValueError ( '<STR_LIT>' % ( key ) ) <EOL> return old_encode_fn ( keys [ key ] ) <EOL> def decode_enum ( encoded ) : <EOL> decoded_value = old_decode_fn ( encoded ) <EOL> if decoded_value not in values : <EOL> if default is not None : <EOL> return default <EOL> else : <EOL> raise ValueError ( <EOL> '<STR_LIT>' % ( decoded_value ) ) <EOL> return values [ decoded_value ] <EOL> enum_field . _encode_fn = encode_enum <EOL> enum_field . _decode_fn = decode_enum <EOL> return enum_field <EOL> return make_enum_field </s>
