swagger-api / swagger-api/swagger-codegen
Use relative imports in generated Python packages
Nobody has claimed this yet.
- Dominant language
- Mustache
- Stars
- 17.8k
- Forks
- 6k
- PR merge metrics
- No merged PRs in 30d
Description
Description
Internally, generated Python code uses absolute imports that hard-code the assumption that users have the package installed top-level with a name like "swagger_server". For example, the following line results in the code from swagger_server import util being generated:
This prevents users from putting the code in a directory with a more semantic name of their choosing, such as "gensrc".
If the generated code instead used relative imports, e.g. from .. import util in this case, then users would be free to move the code into a directory with a name of their choosing, or even nested in a subdirectory so they could import it as from gensrc.swagger_server import util, and then all the generated code's internal imports would still work.
Swagger-codegen version
Using 2.3.1 but believe this occurs in all versions, not a regression.
Steps to reproduce
swagger-codegen --input-spec api.yml \
--output ./desired/subdirectory/on/my/python/path \
--lang python-flask
Related issues/PRs
Only found it mentioned in a comment on a different PR ("change to the name will not fix the problem unfortunately, we need those relative imports"):
https://github.com/swagger-api/swagger-codegen/pull/6839#discussion_r154770878
Suggest a fix/enhancement
Use relative imports.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache and reproduce the generation command using api.yml and the python-flask language. Search the generated Python templates for similar absolute imports, then verify that generated code can be moved under a chosen directory and its internal imports still work.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100