Skip to content

Possibly wrong type annotations in register_structure_hook_factory #281

@sscherfke

Description

@sscherfke
  • cattrs version: 22.1.0
  • Python version: 3.10
  • Operating System: macOS

Description

It seems like the type annotations for Converter.register_structue_hook_factory() are not correct.

They suggest a function signature that, when applied, leads to errors in my tests.

What I Did

My code:

def register_attrs_hook_factory(converter: Converter) -> None:
    """
    Register a hook factory that allows using instances of attrs classes where
    cattrs would normally expect a dictionary.

    These instances are then returned as-is and without further processing.
    """

    def allow_attrs_instances(typ: Any) -> Callable[[Any, Any], Any]:
        # According to mypy, this should be:
        # def structure_attrs(val: Any) -> Any:
        def structure_attrs(val: Any, _: Any) -> Any: 
            if isinstance(val, typ):
                return val
            return converter.structure_attrs_fromdict(val, typ)

        return structure_attrs

    converter.register_structure_hook_factory(has, allow_attrs_instances)  # mypy complains here

Mypy complains when I do def structure_attrs(val: Any, _: Any) -> Any:

src/typed_settings/converters.py:77: error: Argument 2 to "register_structure_hook_factory" of "Converter" 
has incompatible type "Callable[[Any], Callable[[Any, Any], Any]]"; 
expected "Callable[[Any], Callable[[Any], Any]]"  [arg-type]

But pytest complains when I do def structure_attrs(val: Any) -> Any:

typed_settings.exceptions.InvalidValueError: structure_attrs() takes 1 positional argument but 2 were given

IMHO, pytest has the stronger arguments. ;-)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions