貢獻指南

開始使用

支援的 Python 版本

The lowest currently supported version is Python 3.9. At a minimum you will need Python 3.9 for code changes and 3.13 if you plan on doing documentation building / changes.

You can use various tools to manage multiple Python versions on your system including:

We use the lowest supported version in our type-checking CI, this ensures that the changes you made are backward compatible.

Setting up the environment

小訣竅

We maintain a Makefile with several commands to help with common tasks. You can run make help to see a list of available commands.

If you are utilizing GitHub Codespaces, the environment will bootstrap itself automatically. The steps below are for local development.

  1. 安裝 uv

  2. 執行 make install 來建立一個虛擬環境並安裝所需的開發依賴,或手動執行 uv sync 命令:

    安裝開發依賴
    uv sync
    

小訣竅

Many modern IDEs like PyCharm or VS Code will enable the uv-managed virtualenv that is created in step 2 for you automatically. If your IDE / editor does not offer this functionality, then you will need to manually activate the virtualenv yourself. Otherwise you may encounter errors or unexpected behaviour when trying to run the commands referenced within this document.

To activate the virtualenv manually, please consult uv's documentation on working with virtual environments.

The rest of this document will assume this environment is active wherever commands are referenced.

程式碼貢獻

重要

  • Documentation PRs are always welcome; it's often a very good entry point to get familiar with the project.

  • Bug fixes and small improvements are also a good way to get started. There is no shortage of small things that can be improved.

  • We're all humans (hopefully) and may forget about your particular PR. If you feel your PR has stalled, feel free to gently nudge us.

  • Large features or refactors may take time. Please be patient; we're all volunteers and want to ensure the best possible outcome.

  • Use LLMs intelligently. Most PRs automatically generated are not usable, and incur a higher than normal cost from reviewers and maintainers, as they still need to be thoroughly evaluated, even if they are ultimately not acceptable.

工作流程

  1. 分叉 Litestar 儲存庫

  2. Clone your fork locally with git

  3. Set up the environment

  4. Make your changes

  5. (Optional) Run pre-commit run --all-files to run linters and formatters. This step is optional and will be executed automatically by git before you make a commit, but you may want to run it manually in order to apply fixes

  6. Commit your changes to git. We follow conventional commits which are enforced using a pre-commit hook.

  7. 將變更推送到您的分叉庫

  8. Open a pull request. Give the pull request a descriptive title indicating what it changes. The style of the PR title should also follow conventional commits, and this is enforced using a GitHub action.

  9. Add yourself as a contributor using the all-contributors bot

Guidelines for writing code

  • Code should be Pythonic and zen

  • All code should be fully typed. This is enforced via mypy and Pyright

    • When requiring complex types, use a type alias. Check types if a type alias for your use case already exists

    • If something cannot be typed correctly due to a limitation of the type checkers, you may use typing.cast() to rectify the situation. However, you should only use this as a last resort if you've exhausted all other options of type narrowing, such as isinstance() checks and type guards.

    • You may use a properly scoped type: ignore if you ensured that a line is correct, but mypy / pyright has issues with it.

      Properly scoped meaning do not use blank type: ignore, instead supply the specific error code, e.g., type: ignore[attr-defined]

  • If you are adding or modifying existing code, ensure that it's fully tested. 100% test coverage is mandatory, and will be checked on the PR using SonarCloud and Codecov

  • All functions, methods, classes, and attributes should be documented with a docstring. We use the Google docstring style. If you come across a function or method that doesn't conform to this standard, please update it as you go

  • When adding a new public interface, it has to be included in the reference documentation located in docs/reference. If applicable, add or modify examples in the docs related to the new functionality implemented, following the guidelines established in Adding examples.

編寫並執行測試

測試位於 tests 目錄中,並遵循與 litestar 模組相同的目錄結構。如果要增添測試案例,應將其放在 tests 的正確子模組中。例如,針對 litestar/utils/sync.py 的測試應放在 tests/utils/test_sync.py

The Makefile includes several commands for running tests:

  • make test to run tests located in tests

  • make test-examples to run tests located in docs/examples/tests

  • make test-all to run all tests

  • make coverage to run tests with coverage and generate an html report

The tests make use of pytest-xdist to speed up test runs. These are enabled by default when running make test, make test-all or make coverage. Due to the nature of pytest-xdist, attaching a debugger isn't as straightforward. For debugging, it's recommended to run the tests individually with pytest <test name> or via an IDE, which will skip pytest-xdist.

執行型別檢查器

我們使用 mypypyright 來強制執行型別安全。你可以使用以下命令來執行它們:

  • make mypy

  • make pyright

  • make type-check to run both

  • make lint to run pre-commit hooks and type checkers.

Our type checkers are run on Python 3.9 in CI, so you should make sure to run them on the same version locally as well.

Project documentation

The documentation is located in the /docs directory and is written in reStructuredText with the Sphinx. library. If you're unfamiliar with any of those, reStructuredText primer and Sphinx quickstart are recommended reads.

文件主題與外觀

我們歡迎任何能增強或改善文件外觀與易用性的貢獻。我們使用優秀的 PyData Sphinx Theme 主題,其內建了許多開箱即用的選項。如果您希望對文件的樣式、設定或靜態網站生成做出貢獻,應先參閱該主題的文件。

Running the docs locally

You can serve the documentation locally with

Serving the documentation locally
make docs-serve

or build it with

Serving the documentation locally
make docs

撰寫與編輯文件

We welcome contributions that enhance / improve the content of the docs. Feel free to add examples, clarify text, restructure the docs, etc., but make sure to follow these guidelines:

  • Write text in idiomatic English, using simple language

  • Do not use contractions for ease of reading for non-native English speakers

  • Opt for Oxford commas when listing a series of terms

  • Keep examples simple and self contained (see Adding examples). This is to ensure they are tested alongside the rest of the test suite and properly type checked and linted.

  • Provide links where applicable.

  • Use intersphinx wherever possible when referencing external libraries

  • Provide diagrams using Mermaid where applicable and possible

Adding examples

The examples from the docs are located in their own modules inside the /docs/examples folder. This makes it easier to test them alongside the rest of the test suite, ensuring they do not become stale as Litestar evolves.

Please follow the next guidelines when adding a new example:

  • Add the example in the corresponding module directory in /docs/examples or create a new one if necessary

  • Create a suite for the module in /tests/examples that tests the aspects of the example that it demonstrates

  • Reference the example in the rst file with an external reference code block, e.g.

An example of how to use literal includes of external files
.. literalinclude:: /examples/test_thing.py
   :language: python
   :caption: All includes should have a descriptive caption

自動執行範例

Our docs include a Sphinx extension that can automatically run requests against example apps and include their result in the documentation page when its being built. This only requires 2 steps:

  1. Create an example file with an app object in it, which is an instance of Litestar

  2. Add a comment in the form of # run: /hello to the example file

When building the docs (or serving them locally), a process serving the app instance will be launched, and the requests specified in the comments will be run against it. The comments will be stripped from the result, and the output of the curl invocation inserted after the example code-block.

The # run: syntax is nothing special; everything after the colon will be passed to the curl command that's being invoked. The URL is built automatically, so the specified path can just be a path relative to the app.

In practice, this looks like the following:

An example of how to use the automatic example runner
from typing import Dict

from litestar import Litestar, get


@get("/")
def hello_world() -> Dict[str, str]:
    """Handler function that returns a greeting dictionary."""
    return {"hello": "world"}


app = Litestar(route_handlers=[hello_world])

# run: /

This is equivalent to:

An example of how to use the automatic example runner
   from typing import Dict

   from litestar import Litestar, get


   @get("/")
   def hello_world() -> Dict[str, str]:
       """Handler function that returns a greeting dictionary."""
       return {"hello": "world"}


   app = Litestar(route_handlers=[hello_world])

Run it

> curl http://127.0.0.1:8000/
{"hello": "world"}

建立新的發行版

  1. Checkout the main branch:

    Checking out the main branch of the litestar repository
    git checkout main
    
  2. Run the release preparation script:

    Preparing a new release
    python tools/prepare_release.py <new version number> --update-version --create-draft-release
    

    Replace <new version number> with the desired version number following the versioning scheme.

    This script will:

    • Update the version in pyproject.toml

    • Generate a changelog entry in 3.x 變更日誌

    • 在 GitHub 上建立草稿發行版

  3. Review the generated changelog entry in 3.x 變更日誌 to ensure it looks correct.

  4. 將變更送交到 main

    將變更送交到 main 分支
    git commit -am "chore(release): prepare release vX.Y.Z"
    

    vX.Y.Z 替換為實際的版本號。

  5. Create a new branch for the release:

    為發行版建立新的分支
    git checkout -b vX.Y.Z
    
  6. Push the changes to a vX.Y.Z branch:

    Pushing the changes to the vX.Y.Z branch
    git push origin vX.Y.Z
    
  7. Open a pull request from the vX.Y.Z branch to main.

  8. Once the pull request is approved, go to the draft release on GitHub (the release preparation script will provide a link).

  9. Review the release notes in the draft release to ensure they look correct.

  10. If everything looks good, click "Publish release" to make the release official.

  11. Go to the Release Action and approve the release workflow if necessary.

  12. Check that the release workflow runs successfully.

備註

The version number should follow semantic versioning and PEP 440.