Skip to content

TypeError if I use typing generics for output - disable on_invalid globally? #866

@sanzoghenzo

Description

@sanzoghenzo

This is related to #507

I would like to use typing annotations the "normal way", that is to describe the actual return type of a function and not use it as a transformer.

Also, I think that on_invalid should not use the return type from typing annotations by default.
That is the problem I encounter with the following code:

from typing import Dict, Any

import hug


@hug.post("/sample")
def sample_task(text: str, return_empty: bool) -> Dict[str, Any]:
    return {} if return_empty else {"result": text}


api = hug.API(__name__)


if __name__ == '__main__':
    response = hug.test.post(api, "/sample")
    assert response.status == hug.HTTP_400

The error message is forced into a transformation to Dict[str, Any] that fails:

Traceback (most recent call last):
  File "C:/Users/sanzo/source/repos/dp-api/src/test_multiple_modules/main.py", line 15, in <module>
    response = hug.test.post(api, "/sample")
  File "C:\Users\sanzo\AppData\Local\pypoetry\Cache\virtualenvs\dp-api-l3tZMAdC-py3.7\lib\site-packages\hug\test.py", line 91, in call
    response,
  File "C:\Users\sanzo\AppData\Local\pypoetry\Cache\virtualenvs\dp-api-l3tZMAdC-py3.7\lib\site-packages\falcon\api.py", line 269, in __call__
    responder(req, resp, **params)
  File "C:\Users\sanzo\AppData\Local\pypoetry\Cache\virtualenvs\dp-api-l3tZMAdC-py3.7\lib\site-packages\hug\interface.py", line 947, in __call__
    raise exception
  File "C:\Users\sanzo\AppData\Local\pypoetry\Cache\virtualenvs\dp-api-l3tZMAdC-py3.7\lib\site-packages\hug\interface.py", line 915, in __call__
    return self.render_errors(errors, request, response)
  File "C:\Users\sanzo\AppData\Local\pypoetry\Cache\virtualenvs\dp-api-l3tZMAdC-py3.7\lib\site-packages\hug\interface.py", line 819, in render_errors
    data, **self._arguments(self._params_for_on_invalid, request, response)
  File "c:\tools\miniconda3\lib\typing.py", line 668, in __call__
    raise TypeError(f"Type {self._name} cannot be instantiated; "
TypeError: Type Dict cannot be instantiated; use dict() instead

Things get worse if I want to return None and specify Union[None, Dict[str, Any]] as return type.

Using dict works, but then mypy complains about it:

error: Implicit generic "Any". Use "typing.Dict" and specify generic parameters  [type-arg]

If this is a feature and not a bug, is there a way to globally set on_invalid to None?

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