Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A static type analyzer for Python code

License

NotificationsYou must be signed in to change notification settings

google/pytype

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CIPyPI - Wheel

pytype - 🦆✔

Pytype checks and infers types for your Python code - without requiring typeannotations. Pytype can:

  • Lint plain Python code, flagging common mistakes such as misspelled attributenames, incorrect function calls, andmuch more, even acrossfile boundaries.
  • Enforce user-providedtype annotations. While annotations areoptional for pytype, it will check and apply them where present.
  • Generate type annotations in standalone files ("pyi files"),which can be merged back into the Python source with a providedmerge-pyi tool.

Pytype is a static analyzer; it does not execute the code it runs on.

Thousands of projects at Google rely on pytype to keep their Python codewell-typed and error-free.

For more information, check out theuser guide,FAQ, orsupported features.

How is pytype different from other type checkers?

  1. Pytype usesinference instead of gradual typing. This means it willinfer types on code even when the code has no type hints on it. So it candetect issues with code like this, which other type checkers would miss:

    deff():return"PyCon"defg():returnf()+2019# pytype: line 4, in g: unsupported operand type(s) for +: 'str'# and 'int' [unsupported-operands]
  2. Pytype islenient instead of strict. That means it allows alloperations that succeed at runtime and don't contradict annotations. Forinstance, this code will pass as safe in pytype, but fail in other typecheckers, which assign types to variables as soon as they are initialized:

    fromtypingimportListdefget_list()->List[str]:lst= ["PyCon"]lst.append(2019)return [str(x)forxinlst]# mypy: line 4: error: Argument 1 to "append" of "list" has# incompatible type "int"; expected "str"

Also see the correspondingFAQ entry.

Quickstart

To quickly get started with type-checking a file or directory, run thefollowing, replacingfile_or_directory with your input:

pip install pytypepytype file_or_directory

To set up pytype on an entire package, add the following to apyproject.tomlfile in the directory immediately above the package, replacingpackage_namewith the package name:

[tool.pytype]inputs = ['package_name']

Now you can run the no-argument commandpytype to type-check the package. It'salso easy to add pytype to your automated testing; see thisexample of a GitHub project that runs pytype on GitHub Actions.

Finally, pytype generates files of inferred type information, located by defaultin.pytype/pyi. You can use this information to type-annotate thecorresponding source file:

merge-pyi -i<filepath>.py .pytype/pyi/<filename>.pyi

Requirements

You need a Python 3.8-3.12 interpreter to run pytype, as well as aninterpreter in$PATH for the Python version of the code you're analyzing(supported: 3.8-3.12).

Platform support:

  • Pytype is currently developed and tested on Linux*, which is the main supportedplatform.
  • Installation on MacOSX requires OSX 10.7 or higher and Xcode v8 or higher**.
  • Windows is currently not supported unless you useWSL.

*On Alpine Linux, installation may fail due to issues with upstreamdependencies. See the details ofthis issue for apossible fix.
**If the ninja dependency fails to install, make sure cmake is installed. Seethis issue for details.

Installing

Pytype can be installed via pip. Note that the installation requireswheelandsetuptools. (If you're working in a virtualenv, these two packages shouldalready be present.)

pip install pytype

Or from the source codeon GitHub.

git clone --recurse-submodules https://github.com/google/pytype.gitcd pytypepip install.

Instead of using--recurse-submodules, you could also have run

git submodule initgit submodule update

in thepytype directory. To edit the code and have your edits tracked live,replace the pip install command with:

pip install -e.

Installing on WSL

Follow the steps above, but make sure you have the correct libraries first:

sudo apt install build-essential python3-dev libpython3-dev

Usage

usage: pytype [options] input [input ...]positional arguments:  input                 file or directory to process

Common options:

  • -V, --python-version: Python version (major.minor) of the target code.Defaults to the version that pytype is running under.
  • -o, --output: The directory into which all pytype output goes, includinggenerated .pyi files. Defaults to.pytype.
  • -d, --disable. Comma or space-separated list of error names to ignore.Detailed explanations of pytype's error names are inthis doc. Defaults to empty.

For a full list of options, runpytype --help.

In addition to the above, you can direct pytype to use a custom typeshedinstallation instead of its own bundled copy by setting$TYPESHED_HOME.

Config File

For convenience, you can save your pytype configuration in a file. The configfile can be a TOML-style file with a[tool.pytype] section (preferred) or anINI-style file with a[pytype] section. If an explicit config file is notsupplied, pytype will look for a pytype section in the firstpyproject.toml orsetup.cfg file found by walking upwards from the current working directory.

Start off by generating a sample config file:

$ pytype --generate-config pytype.toml

Now customize the file based on your local setup, keeping only the sections youneed. Directories may be relative to the location of the config file, which isuseful if you want to check in the config file as part of your project.

For example, suppose you have the following directory structure and want toanalyze package~/repo1/foo, which depends on package~/repo2/bar:

~/├── repo1│   └── foo│       ├── __init__.py│       └── file_to_check.py└── repo2    └── bar        ├── __init__.py        └── dependency.py

Here is the filled-in config file, which instructs pytype to type-check~/repo1/foo as Python 3.9 code, look for packages in~/repo1 and~/repo2,and ignore attribute errors. Notice that the path to a package does not includethe package itself.

$ cat ~/repo1/pytype.toml# NOTE: All relative paths are relative to the location of this file.[tool.pytype]# Space-separated list of files or directories to process.inputs = ['foo',]# Python version (major.minor) of the target code.python_version ='3.9'# Paths to source code directories, separated by ':'.pythonpath = .:~/repo2# Space-separated list of error names to ignore.disable = ['attribute-error',]

We could've discovered that~/repo2 needed to be added to the pythonpath byrunning pytype's broken dependency checker:

$ pytype --config=~/repo1/pytype.toml ~/repo1/foo/*.py --unresolvedUnresolved dependencies:  bar.dependency

Subtools

Pytype ships with a few scripts in addition topytype itself:

  • annotate-ast, an in-progress type annotator for ASTs.
  • merge-pyi, for merging type information from a .pyi file into aPython file.
  • pytd-tool, a parser for .pyi files.
  • pytype-single, a debugging tool for pytype developers, which analyzes asingle Python file assuming that .pyi files have already been generated for allof its dependencies.
  • pyxref, a cross-references generator.

License

Apache 2.0

Disclaimer

This is not an official Google product.


[8]ページ先頭

©2009-2025 Movatter.jp