Fastapi: Replace relative imports from tutorial with absolute imports to avoid crashes

Created on 14 Sep 2020  路  7Comments  路  Source: tiangolo/fastapi

I had been following the official FastAPI tutorials and I have had many bugs. After some time understanding them and trying to fix, I saw they were due to the usage of relative imports.

Two person in my team had this problem independently and took some hours and tweaks to make a hack to this issue. In stackoverflow i also found many people having headches due to relative imports.

Only later I have found that PEP8 warns about pitfalls of relative imports and strongly advice for usage of absolute imports. After trying this, my code of the FastAPI tutorial worked.

Could you please use absolute imports in your tutorial to avoid this recurrent problem?
Thanks!

Source of recomendation of absolute imports over relative:
https://www.python.org/dev/peps/pep-0008/

All 7 comments

Which tutorials?

The ones in fastapi.tiangolo.com.

From those examples, people in team stared to make more adventurous relative imports and having crashes.

For example:
https://fastapi.tiangolo.com/tutorial/sql-databases/
image
image
https://fastapi.tiangolo.com/tutorial/testing/:
image

Good , you can open a PR :)

How did you fix this? I want to dockerize the thing from the tutorial but don't want to go creating a whole package to fix the issue with imports.

I'm not sure I understand why creating a package is difficult here, or even required? You can update the code you copy from examples to not use relative imports

I'm actually quite curious what the best practice is.

It seems very common that projects don't install as a package but use relative imports.

In the full stack example the PYTHONENV variable is set to give fully qualified imports without installing: https://github.com/tiangolo/full-stack-fastapi-postgresql/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/backend.dockerfile

Is there any reason not to install app as a package? It would be useful in my case because I want to grab the metadata info from the package (e.g. version)

I got this problem too. Whole app run properly but when it comes to running the package alone, there will be a problem.

Was this page helpful?
0 / 5 - 0 ratings