Skip to content

Undefined variable in Custom Coercers snippet from documentation #285

@gilbsgilbs

Description

@gilbsgilbs

Used Cerberus version: 1.0.1


Use-case abstract

I want to be able to set finer error messages when defining custom coercers.


Support request / Bug report

Here is the excerpt from the documentation (http://docs.python-cerberus.org/en/latest/customize.html#custom-coercers):

class MyNormalizer(Validator):
        def __init__(self, multiplier, *args, **kwargs):
            super(MyNormalizer, self).__init__(*args, **kwargs)
            self.multiplier = multiplier

        def _normalize_coerce_multiply(self, value):
            try:
                return value * self.multiplier
            except Exception as e:
                self._error(field, errors.COERCION_FAILED, e)

This code snippet can't work since field variable in the last line is undefined. We either need to pass the field argument to the _normalize_coerce_multiply method or avoid the try/except. Correct me if I am wrong, but I reckon that the try/except is already done in the __normalize_coerce method which would mean that it's just a documentation issue.

Ideally, I would like to be able to define custom error messages in coercers, and generally be finer in the way that I handle my error messages using Cerberus. I have already encountered the same kind of limitation with 1.x custom types. In 0.9, there was no limitation in this regard (field argument was passed to the child method, but that was removed in 1.0 for some reason). This actually prevents me from migrating to Cerberus 1.x in one of my projects (I relied on _error method in a custom type). I think it would be a good idea to pass the field argument everywhere (types, coercers, validators, …) if requested by the child method (maybe using argspec or something similar to prevent breaking changes). But that's maybe a bit out of the scope of this issue.

Many thanks for the amazing work :) .

Gilb's

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions