This proposal solves a problem I have when formatting Field values. I
created a custom Validator class which maps the value None into a string
(such as "N/A" or "NT"), but the mapping was ignored because the current
Field processing provides an early exit if the value of the Field is None,
i.e. it never reaches the Validator object for formatting.
Proposal:
I propose creating a new keyword variable for Field objects, called
"map_none" which is initialized to None for backwards compatibility:
map_none = None,
. . .
self.map_none = map_none
Next, we use the value of map_none as the return value for None from the
formatter function:
def formatter(self, value):
requires = self.requires
if value is None or not self.requires:
return value or self.map_none
Last, for symmetry, we alter the validator to replace any occurrence of
map_none with None when processing items to go back into the database. In
my case it will accept any entered value of "NT" and map it back into None
when storing row data in the database. I would also use it to replace
empty strings with None (which I prefer over empty strings in the database
when values are not entered).
def validate(self, value):
if not self.requires:
return ((value if value!=self.map_none else None), None)
requires = self.requires
if not isinstance(requires, (list, tuple)):
requires = [requires]
for validator in requires:
(value, error) = validator(value)
if error:
return (value, error)
return ((value if value!=self.map_none else None), None)
This approach allows any mapping of None into an object of the user's
choosing, and provides the mapping in a consistent and bi-directional
manner. It preserves all existing behavior of Validators. The only cost
is an additional variable carried in Field objects and the time expended on
the trivial "if" tests to map the value.
Any thoughts?
-- Joe B.
--