I need some kind of thin wrapper object to mark dictionary keys, like:
d = {
Required('name'): str,
Optional('age'): int,
}
And these wrappers should behave like the wrapped object (comparison, hashing, etc):
marked = Required('name')
marked == 'name' #-> True
d[marked] = 'hello'
d['name'] #-> 'hello'
With a single additional property: it should remember the added class:
isinstance(marked, Required) #-> True
and the added class should have custom methods.
This is actually something like a mixin on hashable objects.
I dislike those heavyweight Proxy Patterns which mimic all special properties and thinking of the following idea instead:
class Wrapper(object):
def __new__(cls, value):
value_type = type(value)
Type = type(
value_type.__name__, # same name
(cls, value_type), # Wrapper + bases
{})
Type.__new__ = value_type.__new__ # prevent recursion
return Type(value)
# Override method
def __repr__(self):
return 'Wrapper({})'.format(self)
Better ideas?