Python 7.0pl5 Benutzerhandbuch

Seite von 124
Handling Structured Types
85
ues of the correct type before hand. A service may also override the default decoders for extended types
such as the date and time types if desired.
Handling Structured Types
The encoding mechanism for data does not provide a way of adding support for your own structured
types, whereby the type of that object can also be transmitted. All objects need to be able to be con-
verted into instances of scalar types, dictionaries, tuples or lists. To avoid having to do this conversion
manually, it is however possible to define an encoder for a structured type which will do this for you.
At the global level, such a function is again registered using the "
encoder()
" function. The differ-
ence between this function and that for scalar types however, is that instead of returning a string giving
the name of the scalar type, the value
None
should be returned in its place. The second value in the
tuple should then be the instance of the structured type translated into either a scalar type, dictionary,
tuple or list.
def _encode_UserList(object):
return (None,list(object))
netsvc.encoder(UserList.UserList,_encode_UserList)
Having returned the translated value, it will be represented to the encoder. Thus it is only necessary to
translate the top level of the data structure as enclosed values will in turn be translated automatically
if required and if an encoder is registered. This mechanism may also be used in an encoder specific to
a service.