### Setup Mason and Mason LSPConfig Source: https://pyrefly.org/en/docs/IDE Initialize mason.nvim and mason-lspconfig.nvim plugins for managing language servers. Ensure these plugins are installed via your plugin manager. ```lua require("mason").setup() require("mason-lspconfig").setup() ``` -------------------------------- ### Install and Initialize Pyrefly with Pixi Source: https://pyrefly.org/en/docs/installation Installation and initialization workflow using pixi. ```bash pixi add pyrefly pixi run pyrefly init pixi run pyrefly check --summarize-errors ``` -------------------------------- ### Install and Initialize Pyrefly with uv Source: https://pyrefly.org/en/docs/installation Installation and initialization workflow using uvx. ```bash uvx pyrefly init uvx pyrefly check --summarize-errors ``` -------------------------------- ### Install and Initialize Pyrefly with Poetry Source: https://pyrefly.org/en/docs/installation Installation and initialization workflow using poetry. ```bash poetry add --group dev pyrefly poetry run pyrefly init poetry run pyrefly check --summarize-errors ``` -------------------------------- ### Install and Initialize Pyrefly with Pip Source: https://pyrefly.org/en/docs/installation Standard installation and initialization workflow using pip. ```bash pip install pyrefly pyrefly init pyrefly check --summarize-errors ``` -------------------------------- ### Install and Initialize Pyrefly with Conda Source: https://pyrefly.org/en/docs/installation Installation and initialization workflow using conda-forge. ```bash conda install -c conda-forge pyrefly pyrefly init pyrefly check --summarize-errors ``` -------------------------------- ### Module Globbing Examples Source: https://pyrefly.org/en/docs/configuration Examples of matching Python dotted import paths using the * wildcard. ```text this.is.a.module ``` ```text this.is.*.module ``` ```text *.my.module ``` ```text this.is.* ``` -------------------------------- ### Filesystem Globbing Examples Source: https://pyrefly.org/en/docs/configuration Examples of Unix-style glob patterns used to match Python files and directories. ```text src/**/*.py ``` ```text src, src/, src/*, src/**, and src/**/* ``` ```text ?.py and [A-z].py ``` ```text src/path/to/my/file.py ``` ```text src/**/tests, src/**/tests/, src/**/tests/**, and src/**/tests/**/* ``` -------------------------------- ### Install Pyrefly Source: https://pyrefly.org/en/docs/django Command to install the required version of Pyrefly. ```bash pip install pyrefly ``` -------------------------------- ### Install Django Stubs and Virtual Environment Source: https://pyrefly.org/en/docs/django Commands to set up the necessary environment for Django type checking. ```bash # Install django-stubs pip install django-stubs # Create and activate a virtual environment python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Install and Run Pyrefly Source: https://pyrefly.org/en/docs/python-typing-for-beginners Commands to install the Pyrefly package and execute type checks on files or directories. ```bash # Fast, zero‑config pip install pyrefly pyrefly check ./my_sample.py # Check whole directories pyrefly check app/ tests/ ``` -------------------------------- ### Configure Pyrefly in Neovim Source: https://pyrefly.org/en/docs/IDE Define the language server command for manual setup in Neovim. ```lua ---@type vim.lsp.Config return { cmd = { "pyrefly", "lsp" }, } ``` -------------------------------- ### Configure Pyrefly via LSP initializationOptions Source: https://pyrefly.org/en/docs/IDE Example structure for passing configuration settings during the LSP initialization request in non-VSCode editors. ```json { "pythonPath": "/usr/bin/python3", "commentFoldingRanges": true, "pyrefly": { "displayTypeErrors": "default", "disableLanguageServices": false, "extraPaths": ["/path/to/extra/modules"], "analysis": { "diagnosticMode": "workspace", "importFormat": "absolute", "inlayHints": { "callArgumentNames": "off", "functionReturnTypes": true, "pytestParameters": false, "variableTypes": true }, "showHoverGoToLinks": true }, "disabledLanguageServices": { "definition": false, "declaration": false, "typeDefinition": false, "codeAction": false, "completion": false, "documentHighlight": false, "references": false, "rename": false, "signatureHelp": false, "hover": false, "inlayHint": false, "documentSymbol": false, "semanticTokens": false, "implementation": false } } } ``` -------------------------------- ### Ensure Pyrefly is Installed via Mason Source: https://pyrefly.org/en/docs/IDE Configure mason-lspconfig to automatically install Pyrefly. Alternatively, run `:MasonInstall pyrefly` in Neovim. ```lua require("mason-lspconfig").setup { ensure_installed = { "pyrefly" }, } ``` -------------------------------- ### Configure Pyrefly Search Path Source: https://pyrefly.org/en/docs/installation Example configuration for defining the search path in pyproject.toml. ```toml [tool.pyrefly] search_path = [ "example_directory/..." ] ``` -------------------------------- ### Initialize Pyrefly Configuration Source: https://pyrefly.org/en/docs/pyrefly-faq Use `pyrefly init` to automatically migrate configuration from mypy or pyright. This command simplifies the setup process for new users. ```bash pyrefly init ``` -------------------------------- ### Define Pyrefly SubConfig Resolution Source: https://pyrefly.org/en/docs/configuration Example configuration demonstrating how to use SubConfigs to override settings for specific file paths. ```toml replace-imports-with-any = [ "sympy.*", "*.series", ] ignore-errors-in-generated-code = true # disable `bad-assignment` and `invalid-argument` for the whole project [errors] bad-assignment = false invalid-argument = false [[sub-config]] # apply this to `sub/project/tests/file.py` matches = "sub/project/tests/file.py" # any unittest imports will by typed as `typing.Any` replace-imports-with-any = ["unittest.*"] [[sub-config]] # apply this config to all files in `sub/project` matches = "sub/project/**" # enable `assert-type` errors in `sub/project` [sub-config.errors] assert-type = true [[sub-config]] # apply this config to all files in `sub` matches = "sub/**" # disable `assert-type` errors in `sub` [sub-config.errors] assert-type = false [[sub-config]] # apply this config to all files under `tests` dirs in `sub/` matches = "sub/**/tests/**" # any pytest imports will be typed as `typing.Any` replace-imports-with-any = ["pytest.*"] ``` -------------------------------- ### GitHub Actions CI Configuration Source: https://pyrefly.org/en/docs/installation Example YAML configuration for running Pyrefly in GitHub Actions. ```yaml name: Pyrefly Type Check on: pull_request: branches: [main] workflow_dispatch: # Allows manual triggering from the GitHub UI jobs: typecheck: runs-on: ubuntu-latest steps: - name: Check out code uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 # Install Python dependencies and create environment - name: Install dependencies and run type checking run: | python -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip # Install your dependencies; adjust the following lines as needed pip install -r requirements-dev.txt - name: Install Pyrefly run: pip install pyrefly - name: Run Pyrefly Type Checker run: pyrefly check ``` -------------------------------- ### Simple Pyrefly TOML Configuration Source: https://pyrefly.org/en/docs/configuration Example of a basic `pyrefly.toml` file. Use `project-includes` to specify directories for type checking and `python-platform` to set the assumed platform. The `[errors]` table allows disabling specific error codes. ```toml # set the directory Pyrefly will search for files to type check project-includes = [ "a", "b/c/d", "e" ] # manually set the `sys.platform` Pyrefly will assume when type checking python-platform = "linux" # a table mapping error codes to an `is-enabled` boolean [errors] # disable `bad-assignment` errors bad-assignment = false # disable `bad-return` errors bad-return = false ``` -------------------------------- ### Basic Type Checking Example in Python Source: https://pyrefly.org/en/docs This example demonstrates how Pyrefly catches type mismatches. The first call to `greet` is valid, while the second call passes an integer where a string is expected, which Pyrefly flags as an error. ```python # Example: Basic Type Checking def greet(name: str) -> str: return "Hello, " + name # This works fine since both "World" is a string and greet expects a string message: str = greet("World") # Pyrefly catches this error before runtime due to a type misatch between 42 and "str" # Error: Argument of type 'int' is not assignable to parameter of type 'str' error_message: str = greet(42) ``` -------------------------------- ### Basic Type Annotations Source: https://pyrefly.org/en/docs/typing-for-python-developers Examples of annotating common built-in types like integers, strings, lists, and dictionaries. ```python # Example: Basic Types from typing import reveal_type age: int = 5 reveal_type(age) # revealed type: int age = "oops" name: str = "John" reveal_type(name) # revealed type: str numbers: list[int] = [1, 2, 3] reveal_type(numbers) # revealed type: list[int] names: list[str] = ["John", "Jane"] reveal_type(names) # revealed type: list[str] person: dict[str, str] = {"name": "John", "age": "30"} reveal_type(person) # revealed type: dict[str, str] is_admin = True reveal_type(is_admin) # revealed type: Literal[True] ``` -------------------------------- ### Define ForeignKey Relationship Source: https://pyrefly.org/en/docs/django Basic setup for a many-to-one relationship between models. ```python from django.db import models class Reporter(models.Model): full_name = models.CharField(max_length=70) class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) ``` -------------------------------- ### Defining Fields with Pydantic Source: https://pyrefly.org/en/docs/pydantic Basic setup for defining Pydantic models using Field for validation. ```python from pydantic import BaseModel, Field ``` -------------------------------- ### Define Model with Custom Primary Key Source: https://pyrefly.org/en/docs/django Example showing how Pyrefly infers types for custom primary keys and the pk alias. ```python from django.db import models class Reporter(models.Model): uuid = models.UUIDField(primary_key=True) full_name = models.CharField(max_length=70) reporter = Reporter() reveal_type(reporter.uuid) # Pyrefly infers: UUID reveal_type(reporter.pk) # Pyrefly infers: UUID (pk aliases the custom primary key) ``` -------------------------------- ### Define Nullable ForeignKey Source: https://pyrefly.org/en/docs/django Example showing how Pyrefly handles nullable relationships in type inference. ```python class Article(models.Model): reporter = models.ForeignKey(Reporter, null=True, on_delete=models.CASCADE) article = Article() reveal_type(article.reporter) # Pyrefly infers: Reporter | None ``` -------------------------------- ### Access ForeignKey Forward Relationship Source: https://pyrefly.org/en/docs/django Example showing type inference when accessing a related model instance. ```python article = Article() reveal_type(article.reporter) # Pyrefly infers: Reporter ``` -------------------------------- ### Subclass Method Override with Compatible Signature Source: https://pyrefly.org/en/docs/error-kinds This example demonstrates a valid method override where the subclass method's signature is compatible with the base class. A function accepting `float` can safely accept `int`, making `Sub.f` a valid override for `Base.f`. ```python class Base: def f(self, a: int) -> None: pass class Sub(Base): def f(self, a: float) -> None: pass ``` -------------------------------- ### Override lspconfig Command for Pyrefly Source: https://pyrefly.org/en/docs/IDE Configure lspconfig to use a specific command for Pyrefly, useful for system installations or custom paths. This example shows how to run `uv`-installed Pyrefly without adding it to your system's PATH. ```lua vim.lsp.config('pyrefly', { -- example of how to run `uv` installed Pyrefly without adding to your path cmd = { 'uvx', 'pyrefly', 'lsp' } }) ``` -------------------------------- ### Configure Custom Build System Source: https://pyrefly.org/en/docs/configuration Use the custom type to integrate arbitrary build systems by specifying a command to query targets. ```toml [build-system] type = "custom" command = ["some", "command", "..."] ``` -------------------------------- ### Configure Buck2 Build System Source: https://pyrefly.org/en/docs/configuration Add this block to pyrefly.toml to enable Buck2 integration. Note that this feature is currently unstable. ```toml [build-system] type = "buck" # Optional: The isolation dir for Buck2 to use. isolation-dir = "pyrefly" # Optional: Extra flags passed to Buck2. extras = ["--verbose", "4"] ``` -------------------------------- ### Run Pyrefly on all project files Source: https://pyrefly.org/en/docs/migrating-from-mypy Navigate to your project's root directory and run Pyrefly to check all files within the project. ```bash cd your/project $ pyrefly check ``` -------------------------------- ### Configure infer-with-first-use behavior Source: https://pyrefly.org/en/docs/configuration Demonstrates how the infer-with-first-use setting affects type inference for empty containers. ```python x = [] x.append(1) # x is list[int] x.append("2") # error! ``` ```python x = [] # x is list[Any] x.append(1) # ok x.append("2") # ok ``` -------------------------------- ### Configuring Baseline in Project Files Source: https://pyrefly.org/en/docs/error-suppressions Define the baseline file path in your configuration files to avoid passing the flag on every run. ```toml # pyrefly.toml baseline = "baseline.json" ``` ```toml # pyproject.toml [tool.pyrefly] baseline = "baseline.json" ``` -------------------------------- ### Custom Build System Argument File Format Source: https://pyrefly.org/en/docs/configuration The format of the argument file passed to the custom build system command. ```text -- ... ``` -------------------------------- ### Access Chained Model Fields Source: https://pyrefly.org/en/docs/django Example showing type inference when accessing fields through a related model. ```python reveal_type(article.reporter.full_name) # Pyrefly infers: str ``` -------------------------------- ### Access ForeignKey ID Suffix Source: https://pyrefly.org/en/docs/django Example showing how Pyrefly infers the type of the auto-generated _id field for a ForeignKey. ```python class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) # Django auto-adds: reporter_id: int article = Article() reveal_type(article.reporter_id) # Pyrefly infers: int ``` -------------------------------- ### Define Model with Auto-Generated Primary Key Source: https://pyrefly.org/en/docs/django Example showing how Pyrefly infers the type of the default auto-generated id field. ```python from django.db import models class Reporter(models.Model): full_name = models.CharField(max_length=70) # Django auto-adds: id = models.AutoField(primary_key=True) reporter = Reporter() reveal_type(reporter.id) # Pyrefly infers: int ``` -------------------------------- ### Configure pyrefly.toml Source: https://pyrefly.org/en/docs/configuration Standalone configuration file for defining project paths, environment settings, and error overrides. ```toml project-includes = ["src"] project-excludes = ["**/.[!/.]*", "**/tests"] search-path = ["src"] site-package-path = ["venv/lib/python3.12/site-packages"] python-platform = "linux" python-version = "3.12" python-interpreter-path = "venv/bin/python3" replace-imports-with-any = [ "sympy.*", "*.series", ] ignore-errors-in-generated-code = true # disable `bad-assignment` and `invalid-argument` for the whole project [errors] bad-assignment = false invalid-argument = false [[sub-config]] # apply this to `sub/project/tests/file.py` matches = "sub/project/tests/file.py" # any unittest imports will by typed as `typing.Any` replace-imports-with-any = ["unittest.*"] [[sub-config]] # apply this config to all files in `sub/project` matches = "sub/project/**" # enable `assert-type` errors in `sub/project` [sub-config.errors] assert-type = true ``` -------------------------------- ### Instantiating a Protocol Source: https://pyrefly.org/en/docs/error-kinds This error occurs when trying to create an instance of a protocol class, which is not designed to be instantiated. ```python from typing import Protocol class C(Protocol): ... C() # bad-instantiation ``` -------------------------------- ### Implicitly Defined Attribute Diagnostic Source: https://pyrefly.org/en/docs/error-kinds Attributes assigned to self outside of recognized constructors or setup methods trigger this diagnostic. ```python class C: def __init__(self): self.x = 0 # no error, `__init__` always executes def f(self): self.y = 0 # error, `y` may be undefined if `f` does not execute ``` -------------------------------- ### Enable Language Server in Neovim Source: https://pyrefly.org/en/docs/IDE Activate the Pyrefly language server within a Neovim session. ```lua vim.lsp.enable({"pyrefly"}) ``` -------------------------------- ### Attribute access restriction Source: https://pyrefly.org/en/docs/error-kinds This error indicates that an attribute exists but cannot be used in the current context. For example, classes do not have access to their instances' attributes. ```python class Ex: def __init__(self) -> None: self.meaning: int = 42 del Ex.meaning # no-access ``` -------------------------------- ### Custom Build System JSON Output Structure Source: https://pyrefly.org/en/docs/configuration The expected JSON output format from a custom build system command. ```json { "root": "/path/to/this/repository", "db": { "//colorama:py-stubs": { "srcs": { "colorama": [ "colorama/__init__.pyi" ] }, "deps": [], "buildfile_path": "colorama/BUCK", "python_version": "3.12", "python_platform": "linux" }, "//colorama:py": { "srcs": { "colorama": [ "colorama/__init__.py" ] }, "deps": ["//colorama:py-stubs"], "buildfile_path": "colorama/BUCK", "python_version": "3.12", "python_platform": "linux" }, "//colorama:colorama": { "alias": "//colorama:py" } } } ``` -------------------------------- ### Class with Type Hints and Bug Source: https://pyrefly.org/en/docs/python-typing-for-beginners A class with type hints for its attributes. The example contains a typo ('hieght') that would be caught by a type checker before runtime. ```python class Rectangle: width: int height: int def __init__(self, width: int, height: int) -> None: self.width = width self.height = height rect = Rectangle(width=100, height=50) area = rect.width * rect.hieght print(area) ``` -------------------------------- ### Implement Root Models Source: https://pyrefly.org/en/docs/pydantic Demonstrates the use of RootModel for custom type validation and strict integer enforcement. ```python from pydantic import RootModel, StrictInt class IntRootModel(RootModel[int]): pass class StrictIntRootModel(RootModel[StrictInt]): pass m1 = IntRootModel(123) # OK m2 = IntRootModel("123") # OK - lax mode allows string-to-int coercion m3 = StrictIntRootModel("123") # Error: StrictInt doesn't allow coercion ``` -------------------------------- ### Migrate Pyright configuration Source: https://pyrefly.org/en/docs/migrating-from-pyright Automatically transform an existing Pyright configuration into a Pyrefly-compatible format. ```bash $ pyrefly init path/to/your/project ``` -------------------------------- ### Run Pyrefly Type Checker in CI Source: https://pyrefly.org/en/docs/installation Add this step to your CI workflow to automatically run Pyrefly's type checker. Ensure Pyrefly is installed in your environment. ```yaml - name: Run Pyrefly Type Checker run: pyrefly check ``` -------------------------------- ### Configuration Options Source: https://pyrefly.org/en/docs/configuration Details on specific configuration keys used to control Pyrefly behavior. ```APIDOC ## Configuration Options ### enabled-ignores - **Type**: list of tools - **Default**: ["type", "pyrefly"] - **Description**: Defines the set of tools from which Pyrefly should respect ignore directives. ### sub-config - **Type**: TOML array of tables - **Default**: [] - **Description**: Overrides specific config values for matched paths in the project. ### recursion-depth-limit - **Type**: integer - **Default**: 0 - **Description**: Maximum recursion depth before triggering overflow protection. Used for debugging stack overflow issues. ### recursion-overflow-handler - **Type**: string ("break-with-placeholder" | "panic-with-debug-info") - **Default**: "break-with-placeholder" - **Description**: Defines how to handle recursion depth limit exceedance. ``` -------------------------------- ### Defining Missing Name in __all__ Source: https://pyrefly.org/en/docs/error-kinds To resolve the `bad-dunder-all` error, ensure all names listed in `__all__` are defined within the module. This example shows how to define a previously missing name. ```python __all__ = ["x", "y"] x = 5 y = 10 # Now `y` is defined ``` -------------------------------- ### Managing Baseline Files Source: https://pyrefly.org/en/docs/error-suppressions Configure baseline files to ignore existing errors and report only new ones. ```bash pyrefly check --baseline="" --update-baseline ``` ```bash pyrefly check --baseline="" ``` -------------------------------- ### Default pyrefly.toml Configuration Source: https://pyrefly.org/en/docs/configuration Standard configuration template showing default project inclusion, exclusion, and search path settings. ```toml ###### configuring what to type check and where to import from # check all Python files under the containing directory project-includes = ["**/*.py*"] # exclude some uninteresting files project-excludes = ["**/node_modules", "**/__pycache__", "**/*venv/**", "**/.[!/.]*/**"] # perform an upward search for `.gitignore`, `.ignore`, and `.git/info/exclude`, and # add those to `project-excludes` automatically use-ignore-files = true # import project files from "." search-path = ["."] # let Pyrefly try to guess your search path disable-search-path-heuristics = false # do not include any third-party packages (except those provided by an interpreter) site-package-path = [] ``` -------------------------------- ### Incorrect TypeVar Definitions in Pyrefly Source: https://pyrefly.org/en/docs/error-kinds Shows examples of incorrect `TypeVar` definitions, including old-style `TypeVars` not being assigned and PEP 695 `TypeVars` with insufficient constraints. Mixing styles is also illegal. ```python from typing import TypeVar # Old-style TypeVars must be assigned to a matching variable. Wrong = TypeVar("Name") # PEP 695-style TypeVars can be constrained, but there must be at least two: def only_one_constraint[T: (int,)](x: T) -> T: ... # It's also illegal to mix the two styles together. T = TypeVar("T") def mixed[S](a: S, b: T) -> None: ... ``` -------------------------------- ### Run Pyrefly on a project Source: https://pyrefly.org/en/docs/migrating-from-pyright Execute type checking on all files within the current project root. ```bash $ cd your/project $ pyrefly check ``` -------------------------------- ### Migrate Mypy config to Pyrefly Source: https://pyrefly.org/en/docs/migrating-from-mypy Use the `pyrefly init` command to automatically convert your existing Mypy configuration (`mypy.ini` or `pyproject.toml`) to a Pyrefly configuration (`pyrefly.toml` or `[tool.pyrefly]`). ```bash $ pyrefly init path/to/your/project ``` -------------------------------- ### Environment Autoconfiguration Source: https://pyrefly.org/en/docs/configuration Explains the logic used by Pyrefly to automatically detect Python interpreter settings. ```APIDOC ## Environment Autoconfiguration ### Description Pyrefly attempts to query a Python interpreter to determine `python-platform`, `python-version`, and `site-package-path` unless `skip-interpreter-query` is set. ### Detection Logic 1. Use CLI flags: `python-interpreter-path`, `fallback-python-interpreter-name`, or `conda-environment`. 2. Detect active `venv` or `conda` environment (prioritizes `venv`). 3. Use config file settings: `python-interpreter-path`, `fallback-python-interpreter-name`, or `conda-environment`. 4. Search for `venv` at project root. 5. Query system interpreters via `which python3` or `which python`. 6. Fall back to default values. ### Queried Attributes - **python-platform**: `sys.platform` - **python-version**: `sys.version_info[:3]` - **site-package-path**: `site.getsitepackages() + [site.getusersitepackages()]` ``` -------------------------------- ### Subclass Method Override with Incompatible Signature Source: https://pyrefly.org/en/docs/error-kinds This error occurs when a subclass method's signature is incompatible with its base class method, violating the Liskov Substitution Principle. For example, a method accepting `int` cannot be overridden by one accepting `str` if the base class expects `int`. ```python class Base: def f(self, a: int) -> None: pass class NoArg(Base): def f(self) -> None: pass class WrongType(Base): def f(self, a: str) -> None: pass def uses_f(b: Base) -> None: b.f(1) ``` -------------------------------- ### Configure Lax and Strict Mode Validation Source: https://pyrefly.org/en/docs/pydantic Demonstrates the difference between default lax mode, which allows type coercion, and strict mode, which enforces exact types. ```python class User(BaseModel): name: str age: int # This passes at runtime and in Pyrefly because age accepts strings in lax mode y = User(name="Alice", age="30") # Strict mode: enforce exact types, no coercion class User2(BaseModel): name: str age: int = Field(strict=True) # This triggers type errors in Pyrefly and red squiggles in the IDE, # and will also fail at runtime due to type mismatch. z = User2(name="Alice", age="30") # Error: age expects int, not str ``` -------------------------------- ### Configure coc.nvim for Pyrefly Source: https://pyrefly.org/en/docs/IDE Add Pyrefly to coc-settings.json to enable language server support in Vim/Neovim. ```json "languageserver": { "pyrefly": { "command": "pyrefly", "args": ["lsp"], "filetypes": ["python"], "rootPatterns": ["pyrefly.toml", "pyproject.toml", ".git"], } }, ``` ```json "languageserver": { "pyrefly": { "command": "pyrefly", "args": ["lsp"], "filetypes": ["python"], "rootPatterns": ["pyrefly.toml", "pyproject.toml", ".git"], "initializationOptions": { "pyrefly": { "displayTypeErrors": "force-on" } } } } ``` -------------------------------- ### Generate or Update Baseline File Source: https://pyrefly.org/en/docs/configuration Use this command to create or refresh the baseline JSON file for suppressing existing type errors. ```bash pyrefly check --baseline="" --update-baseline ``` -------------------------------- ### Function without vs. with Type Hints Source: https://pyrefly.org/en/docs/python-typing-for-beginners Compares a function lacking type hints with one that clearly defines parameter and return types for better clarity and bug prevention. ```python def repeat(text, times): return text * times ``` ```python def repeat(text: str, times: int) -> str: return text * times ``` -------------------------------- ### Configure pyproject.toml Source: https://pyrefly.org/en/docs/configuration Configuration embedded within a pyproject.toml file using the [tool.pyrefly] namespace. ```toml ... # Pyrefly header [tool.pyrefly] #### configuring what to type check and where to import from project-includes = ["src"] project-excludes = ["**/.[!/.]*", "**/tests"] search-path = ["src"] site-package-path = ["venv/lib/python3.12/site-packages"] #### configuring your python environment python-platform = "linux" python-version = "3.12" python-interpreter-path = "venv/bin/python3" #### configuring your type check settings replace-imports-with-any = [ "sympy.*", "*.series", ] ignore-errors-in-generated-code = true [tool.pyrefly.errors] bad-assignment = false invalid-argument = false [[tool.pyrefly.sub-config]] # apply this config to all files in `sub/project` matches = "sub/project/**" # enable `assert-type` errors in `sub/project` [tool.pyrefly.sub-config.errors] assert-type = true [[tool.pyrefly.sub-config]] # apply this config to all files in `sub` matches = "sub/**" # disable `assert-type` errors in `sub/project` [tool.pyrefly.sub-config.errors] assert-type = false # other non-Pyrefly configs ... ``` -------------------------------- ### Configure Eglot for Emacs Source: https://pyrefly.org/en/docs/IDE Register Pyrefly with Eglot to provide language server capabilities. ```elisp (add-to-list 'eglot-server-programs `((python-ts-mode python-mode) . ("pyrefly" "lsp"))) ``` ```elisp (use-package eglot :ensure t :hook ((python-mode python-ts-mode) . eglot-ensure) :config (add-to-list 'eglot-server-programs `((python-ts-mode python-mode) . ("pyrefly" "lsp")))) ``` -------------------------------- ### Configure Pyrefly in Zed Source: https://pyrefly.org/en/docs/IDE Add this configuration to your Zed settings to enable Pyrefly as a language server for Python. Ensure the binary path correctly points to your Pyrefly executable. ```json { "lsp": { "pyrefly": { "binary": { "path": ".venv/bin/pyrefly", "arguments": ["lsp"] } } }, "languages": { "Python": { "language_servers": ["pyrefly"] } } } ``` -------------------------------- ### Compare Mypy and Pyrefly Type Inference Source: https://pyrefly.org/en/docs/django Illustrates how Pyrefly treats manager types as identical across different models, unlike Mypy's plugin approach. ```python from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) authors = models.ManyToManyField(Author, related_name="books") class Article(models.Model): headline = models.CharField(max_length=200) authors = models.ManyToManyField(Author, related_name="articles") # What types do the managers have? book = Book() article = Article() ``` -------------------------------- ### Function Type Annotations Source: https://pyrefly.org/en/docs/typing-for-python-developers Defining parameter and return types for functions to improve IDE navigation and code safety. ```python # Example: Functions from typing import reveal_type def greet(name: str) -> str: return f"Hello, {name}!" greet("Pyrefly") def whatDoesThisFunctionReturnAgain(a: int, b: int): return a + b reveal_type(whatDoesThisFunctionReturnAgain(2, 3)) # revealed type: int ``` -------------------------------- ### Configure ALE for Vim Source: https://pyrefly.org/en/docs/IDE Register Pyrefly as a linter within the ALE configuration. ```vim let g:ale_linters = { ... \ 'python': ['pyrefly'], ... \ } ``` -------------------------------- ### Annotate Variable-Length Arguments Source: https://pyrefly.org/en/docs/python-typing-for-beginners Use type aliases and variadic arguments to define complex function signatures. ```python # Variable length functions from collections.abc import Callable Logger = Callable[[str], None] def debug(*msgs: str, log: Logger | None) -> None:   for m in msgs:     if log is not None:       log(m)     else:       print(m) ``` -------------------------------- ### Upgrading Pyrefly Workflow Source: https://pyrefly.org/en/docs/error-suppressions Use these steps to suppress new errors introduced by upgrades and clean up unused suppressions. ```bash # step 1 pyrefly suppress ``` ```bash # step 2 ``` ```bash # step 3 pyrefly suppress --remove-unused ``` -------------------------------- ### Configure Helix Language Server Source: https://pyrefly.org/en/docs/IDE Add Pyrefly to the languages.toml file for Helix integration. ```toml [language-server.pyrefly] command = "pyrefly" args = ["lsp"] [[language]] name = "python" language-servers = ["pyrefly"] ``` -------------------------------- ### Function with Type Hints Source: https://pyrefly.org/en/docs/python-typing-for-beginners Indicates that the 'name' parameter should be a string and the function returns None. ```python def greet(name: str) -> None: print(f"Hello, {name}!") ``` -------------------------------- ### Upgrade Workflow for Type Errors Source: https://pyrefly.org/en/docs/installation Step-by-step process to suppress errors, format code, and remove unused suppressions. ```bash # Step 1 pyrefly suppress ``` ```bash # Step 2 ``` ```bash # Step 3 pyrefly suppress --remove-unused ``` -------------------------------- ### Configure Alias Validation Source: https://pyrefly.org/en/docs/pydantic Shows how to enable validation by both field name and alias using model configuration. ```python from pydantic import BaseModel, Field class Model(BaseModel, validate_by_name=True, validate_by_alias=True): x: int = Field(alias='y') # both `x` and `y` are valid aliases Model(x=0) Model(y=0) ``` -------------------------------- ### Enable Inline PR Annotations Source: https://pyrefly.org/en/docs/installation Command to output type errors in a format compatible with GitHub Actions PR annotations. ```yaml - name: Run Pyrefly Type Checker run: pyrefly check --output-format=github ``` -------------------------------- ### Run pyrefly report Source: https://pyrefly.org/en/docs/report Execute the report command on specific files or directories to generate type coverage statistics. ```bash pyrefly report path/to/file.py pyrefly report path/to/directory/ ``` -------------------------------- ### Buck2 Integration Command Source: https://pyrefly.org/en/docs/configuration The command invoked internally by Pyrefly when using the Buck2 build system integration. ```bash buck2 [--isolation-dir ] bxl --reuse-current-config [...] prelude//python/sourcedb/pyrefly.bxl:main @ ``` -------------------------------- ### Basic Type Inference Source: https://pyrefly.org/en/docs/typing-for-python-developers Demonstrates how static analyzers infer types from variable assignments and function definitions. ```python # Basic Inference from typing import reveal_type answer = 42 reveal_type(answer) # hover to reveal type fruits: list[str] = ["apple", "banana", "cherry"] scores: dict[str, int] = {"math": 95, "science": 90} def greet(name) -> str: return f"Hello, {name}!" message: str = greet("World") ``` -------------------------------- ### Configure Minimum Severity Source: https://pyrefly.org/en/docs/configuration Sets the minimum severity level for CLI output. This is a project-level setting that cannot be overridden in sub-config sections. ```toml [tool.pyrefly] min-severity = "warn" ``` -------------------------------- ### Generate Python stubs with Pyrefly Source: https://pyrefly.org/en/docs/stubgen Use the stubgen command to process individual files or entire directories. Generated files are saved to the out/ directory by default. ```bash pyrefly stubgen path/to/file.py # or pyrefly stubgen path/to/directory/ ``` -------------------------------- ### Manage Extra Fields in Models Source: https://pyrefly.org/en/docs/pydantic Shows how to control whether models accept or forbid extra fields using the extra configuration parameter. ```python from pydantic import BaseModel # Extra fields allowed by default class ModelAllow(BaseModel): x: int # This works fine: extra field `y` is allowed and ignored ModelAllow(x=1, y=2) # Explicitly forbid extra fields by setting `extra='forbid'` class ModelForbid(BaseModel, extra="forbid"): x: int # This will raise a type error because of unexpected field `y`, which is consistent with runtime behavior. ModelForbid(x=1, y=2) ``` -------------------------------- ### Enable Type Error Squiggles Source: https://pyrefly.org/en/docs/IDE Configure the language server settings to force-on type error displays. ```lua { settings = { python = { pyrefly = { displayTypeErrors = 'force-on' } } } } ``` -------------------------------- ### Structural Typing with Protocols Source: https://pyrefly.org/en/docs/typing-for-python-developers Defines a `Writer` protocol and demonstrates structural typing by passing an object with a compatible `write` method to a function expecting a `Writer`. ```python from typing import Iterable, Protocol class Writer(Protocol): def write(self) -> None: ... class GoodWorld: def write(self) -> None: print("Hello world!") class BadWorld: pass def f(writer: Writer) -> None: pass f(GoodWorld()) # OK f(BadWorld()) # ERROR! ``` -------------------------------- ### Enable Pyrefly to respect Mypy ignore comments Source: https://pyrefly.org/en/docs/migrating-from-mypy Set `permissive-ignores` to `true` to allow Pyrefly to recognize and process `# mypy: ignore` and `# mypy: ignore-errors` comments. ```ini # Direct Pyrefly to respect `# mypy: ignore` and `# mypy: ignore-errors` comments permissive-ignores = true ``` -------------------------------- ### Run Pyrefly Report for Type Coverage Source: https://pyrefly.org/en/docs/pyrefly-faq Use the `pyrefly report` command to measure type coverage across your codebase. This tool helps identify areas lacking type annotations. ```bash pyrefly report ``` -------------------------------- ### Annotate Simple Functions Source: https://pyrefly.org/en/docs/python-typing-for-beginners Define parameter and return types for functions to ensure type safety during calls. ```python # Simple function def add(a: int, b: int) -> int: return a + b ``` -------------------------------- ### Run Pyrefly Infer command Source: https://pyrefly.org/en/docs/autotype Execute the infer command on a specific file or an entire directory to generate type annotations. ```bash pyrefly infer path/to/file.py # or pyrefly infer path/to/directory/ ``` -------------------------------- ### Transform Mypy per-module ignore_missing_imports to Pyrefly replace_imports_with_any Source: https://pyrefly.org/en/docs/migrating-from-mypy Migrates Mypy's `ignore_missing_imports` per-module configuration to Pyrefly's `replace_imports_with_any` list format. ```ini [mypy-some.*.module] ignore_missing_imports = True ``` ```ini replace_imports_with_any = ["some.*.module"] ```