New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Callable type #279

Closed
dmfigol opened this Issue Oct 17, 2018 · 1 comment

Comments

Projects
None yet
2 participants
@dmfigol
Copy link

dmfigol commented Oct 17, 2018

Feature Request

It would be great if pydantic supported callables as types.
Use-case: a user can specify a path to the class to be used dynamically or to provide a callable object directly (instead of the path as a string). We wanted to use pre validator to transform a string to the callable object.

from typing import Type, Callable, Any
from pydantic import BaseModel

def useless(x: Any) -> Any:
    return x

class DemoModel(BaseModel):
    t: Callable[..., Any]


print(DemoModel(t=useless))
...
-> % python main.py
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    class DemoModel(BaseModel):
  File ".../.venv/lib/python3.7/site-packages/pydantic/main.py", line 124, in __new__
    config=config,
  File ".../.venv/lib/python3.7/site-packages/pydantic/fields.py", line 107, in infer
    schema=schema,
  File ".../.venv/lib/python3.7/site-packages/pydantic/fields.py", line 87, in __init__
    self.prepare()
  File ".../.venv/lib/python3.7/site-packages/pydantic/fields.py", line 135, in prepare
    self._populate_sub_fields()
  File ".../.venv/lib/python3.7/site-packages/pydantic/fields.py", line 240, in _populate_sub_fields
    assert issubclass(origin, Mapping)
AssertionError
@samuelcolvin

This comment has been minimized.

Copy link
Owner

samuelcolvin commented Oct 17, 2018

entirely possible as far as I'm concerned.

There might be some complex logic required using inspect to check that the callable arguments match the declaration, but maybe that's not required at this stage?

PR welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment