Skip to content

Dependencies imported from file with python annotations don't work #446

@LKay

Description

@LKay

Describe the bug

When there is a file that contains python annotations import at the top and contains some async function returning parameters dependency injection doesn't work.

To Reproduce

Create file deps.py:

from __future__ import annotation

async def test(foo: Optional[str] = None):
  return foo

And then in the other file containing route definition:

from .deps import test

@api.get("/foo")
async def foo_route(foo: Optional[str] = Depends(test)):
  return None

Trying to run the app with such configuration results in error:

...
  File "/Users/user/.local/share/virtualenvs/pilgrim-api-A9HJbenQ/lib/python3.7/site-packages/fastapi/dependencies/utils.py", line 179, in get_dependant
    param_field = get_param_field(param=param, default_schema=params.Query)
  File "/Users/user/.local/share/virtualenvs/pilgrim-api-A9HJbenQ/lib/python3.7/site-packages/fastapi/dependencies/utils.py", line 265, in get_param_field
    schema=schema,
  File "/Users/user/.local/share/virtualenvs/pilgrim-api-A9HJbenQ/lib/python3.7/site-packages/pydantic/fields.py", line 112, in __init__
    self.prepare()
  File "/Users/user/.local/share/virtualenvs/pilgrim-api-A9HJbenQ/lib/python3.7/site-packages/pydantic/fields.py", line 178, in prepare
    self._populate_validators()
  File "/Users/user/.local/share/virtualenvs/pilgrim-api-A9HJbenQ/lib/python3.7/site-packages/pydantic/fields.py", line 269, in _populate_validators
    *(get_validators() if get_validators else list(find_validators(self.type_, self.model_config))),
  File "/Users/user/.local/share/virtualenvs/pilgrim-api-A9HJbenQ/lib/python3.7/site-packages/pydantic/validators.py", line 470, in find_validators
    raise RuntimeError(f'error checking inheritance of {type_!r} (type: {display_as_type(type_)})') from e
RuntimeError: error checking inheritance of 'Optional[str]' (type: str)

Expected behavior
It runs and works.

Environment:

  • OS: macOS
  • FastAPI Version: 0.35
  • Python: 3.7.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions