Module svnmailer.typedstruct
Typed Data Structures
This module provides helpers for creating typed data structures.
Basic Usage
In order to create a new data structure, you inherit from
Struct
and define the members like so (the booleans are
explained later):
class MyStruct(typedstruct.Struct):
__slots__ = typedstruct.members(locals(), {
'name1': None,
# ... and/or ...
'name2': <type>,
# ... and/or ...
'name3': (<type>, <param>),
})
If there are no fixed types at all (always None
, you
can still benefit from the features of the Struct
class and further write it a bit
simpler:
class MyStruct(typedstruct.Struct):
__slots__ = typedstruct.members(locals(), (
'name1', 'name2', ...
))
Well, the main reason for using the Struct class is to get some
level of type safety and automatic conversion without a complex
written definition of property
for each and every member
(it uses some property like descriptors internally, however). This
encapsulates a lot of ugly logic and error handling (more or less)
into a single piece of code and makes the member definitions
much easier to read and maintain. For example, you can create
a struct member of type regex
. Now you assign a string
to this member and it is automatically compiled to a regex, which you
get, if you retrieve the value later. As you'll see, the
regex
type needs to be defined as a class which should
be inherited from the MemberDescriptor
class and assigned to
the regex
type name via a type mapping dict:
class RegexMember(typedstruct.MemberDescriptor):
def transform(self, value, arg):
import re
return re.compile(value)
# ...
typemap = {'regex': RegexMember}
# ...
class MyStruct(typedstruct.Struct):
__slots__ = typedstruct.members(locals(), {
'checker': 'regex',
}, typemap = typemap)
# ...
store = MyStruct()
store.checker = r'[a-zA-Z]$'
# ...
if store.checker.match(stringtocheck):
# do something
Constraints
Member names must be valid python identifiers. Further all names
starting and ending with underscores are reserved for Struct
's or python's own purposes.
Function Summary |
list
|
members (space,
the_members,
aliases,
typemap)
supply the member and slot entries |
members(space,
the_members,
aliases=None,
typemap=None)
supply the member and slot entries
-
- Parameters:
space -
The namespace to pollute
(type=dict )
the_members -
The member list / description
(type=tuple or dict )
aliases -
The member name aliases
(type=dict )
typemap -
The type mapping table
(type=dict )
- Returns:
-
The list of __slots__ to use.
(type=list )
|