Collection of library stubs for Python, with static types

Overview

typeshed

Build status Chat at https://gitter.im/python/typing Pull Requests Welcome

About

Typeshed contains external type annotations for the Python standard library and Python builtins, as well as third party packages as contributed by people external to those projects.

This data can e.g. be used for static analysis, type checking or type inference.

For information on how to use typeshed, read below. Information for contributors can be found in CONTRIBUTING.md. Please read it before submitting pull requests; do not report issues with annotations to the project the stubs are for, but instead report them here to typeshed.

Typeshed supports Python versions 2.7 and 3.6 and up.

Using

If you're just using mypy (or pytype or PyCharm), as opposed to developing it, you don't need to interact with the typeshed repo at all: a copy of standard library part of typeshed is bundled with mypy. And type stubs for third party packages and modules you are using can be installed from PyPI. For example, if you are using six and requests, you can install the type stubs using

$ pip install types-six types-requests

These PyPI packages follow PEP 561 and are automatically generated by typeshed internal machinery. Also starting from version 0.900 mypy will provide an option to automatically install missing type stub packages (if found on PyPI).

PyCharm, pytype etc. work in a similar way, for more details see documentation for the type-checking tool you are using.

Format

Each Python module is represented by a .pyi "stub file". This is a syntactically valid Python file, although it usually cannot be run by Python 3 (since forward references don't require string quotes). All the methods are empty.

Python function annotations (PEP 3107) are used to describe the signature of each function or method.

See PEP 484 for the exact syntax of the stub files and CONTRIBUTING.md for the coding style used in typeshed.

Directory structure

stdlib

This contains stubs for modules in the Python standard library -- which includes pure Python modules, dynamically loaded extension modules, hard-linked extension modules, and the builtins. VERSIONS file lists the oldest supported Python version where the module is available. In the stdlib/@python2 subdirectory you can find Python 2 versions of the stub files that must be kept different for Python 2 and 3, like builtins.pyi.

stubs

Modules that are not shipped with Python but have a type description in Python go into stubs. Each subdirectory there represents a PyPI distribution, and contains the following:

  • METADATA.toml that specifies oldest version of the source library for which the stubs are applicable, supported Python versions (Python 3 defaults to True, Python 2 defaults to False), and dependency on other type stub packages.
  • Stubs (i.e. *.pyi files) for packages and modules that are shipped in the source distribution. Similar to standard library, if the Python 2 version of the stubs must be kept separate, it can be put in a @python subdirectory.
  • (Rarely) some docs specific to a given type stub package in README file.

No other files are allowed in stdlib and stubs. When a third party stub is modified, an updated version of the corresponding distribution will be automatically uploaded to PyPI shortly (within few hours).

For more information on directory structure and stub versioning, see the relevant section of CONTRIBUTING.md.

Third-party packages are generally removed from typeshed when one of the following criteria is met:

  • The upstream package ships a py.typed file for at least 6-12 months, or
  • the package does not support any of the Python versions supported by typeshed.

Contributing

Please read CONTRIBUTING.md before submitting pull requests. If you have questions related to contributing, drop by the typing Gitter.

Running the tests

The tests are automatically run on every PR and push to the repo.

There are several tests:

  • tests/mypy_test.py tests typeshed with mypy
  • tests/pytype_test.py tests typeshed with pytype.
  • tests/mypy_self_check.py checks mypy's code base using this version of typeshed.
  • tests/mypy_test_suite.py runs a subset of mypy's test suite using this version of typeshed.
  • tests/check_consistent.py checks certain files in typeshed remain consistent with each other.
  • tests/stubtest_test.py checks stubs against the objects at runtime.
  • flake8 enforces a style guide.

Setup

Run:

$ python3.6 -m venv .venv3
$ source .venv3/bin/activate
(.venv3)$ pip install -U pip
(.venv3)$ pip install -r requirements-tests-py3.txt

This will install mypy (you need the latest master branch from GitHub), typed-ast, flake8 (and plugins), pytype, black and isort.

mypy_test.py

This test requires Python 3.6 or higher; Python 3.6.1 or higher is recommended. Run using:(.venv3)$ python3 tests/mypy_test.py

This test is shallow — it verifies that all stubs can be imported but doesn't check whether stubs match their implementation (in the Python standard library or a third-party package). It has an exclude list of modules that are not tested at all, which also lives in the tests directory.

If you are in the typeshed repo that is submodule of the mypy repo (so .. refers to the mypy repo), there's a shortcut to run the mypy tests that avoids installing mypy:

$ PYTHONPATH=../.. python3 tests/mypy_test.py

You can restrict mypy tests to a single version by passing -p2 or -p3.9:

$ PYTHONPATH=../.. python3 tests/mypy_test.py -p3.9
running mypy --python-version 3.9 --strict-optional # with 342 files

pytype_test.py

This test requires Python 2.7 and Python 3.6. Pytype will find these automatically if they're in PATH, but otherwise you must point to them with the --python27-exe and --python36-exe arguments, respectively. Run using: (.venv3)$ python3 tests/pytype_test.py

This test works similarly to mypy_test.py, except it uses pytype.

mypy_self_check.py

This test requires Python 3.6 or higher; Python 3.6.1 or higher is recommended. Run using: (.venv3)$ python3 tests/mypy_self_check.py

This test checks mypy's code base using mypy and typeshed code in this repo.

mypy_test_suite.py

This test requires Python 3.5 or higher; Python 3.6.1 or higher is recommended. Run using: (.venv3)$ python3 tests/mypy_test_suite.py

This test runs mypy's own test suite using the typeshed code in your repo. This will sometimes catch issues with incorrectly typed stubs, but is much slower than the other tests.

check_consistent.py

Run using: python3 tests/check_consistent.py

stubtest_test.py

This test requires Python 3.6 or higher. Run using (.venv3)$ python3 tests/stubtest_test.py

This test compares the stdlib stubs against the objects at runtime. Because of this, the output depends on which version of Python and on what kind of system it is run. Thus the easiest way to run this test is via Github Actions on your fork; if you run it locally, it'll likely complain about system-specific differences (in e.g, socket) that the type system cannot capture. If you need a specific version of Python to repro a CI failure, pyenv can help.

Due to its dynamic nature, you may run into false positives. In this case, you can add to the whitelists for each affected Python version in tests/stubtest_whitelists. Please file issues for stubtest false positives at mypy.

To run stubtest against third party stubs, it's easiest to use stubtest directly, with (.venv3)$ python3 -m mypy.stubtest --custom-typeshed-dir <path-to-typeshed> <third-party-module>. stubtest can also help you find things missing from the stubs.

flake8

flake8 requires Python 3.6 or higher. Run using: (.venv3)$ flake8

Note typeshed uses the flake8-pyi and flake8-bugbear plugins.

Comments
  • Explore building third party stubs as packages

    Explore building third party stubs as packages

    This is an alternative to #2440 (disallowing third-party stubs). The idea is that typeshed remains/becomes a central repository for third-party stubs that are not bundled with the parent package, similar to DefinitelyTyped. In the future I expect type checkers will not want to bundle all third-party stubs for a variety of reasons, so third-party stubs would be distributed as separate PEP 561 stub-only packages, one per upstream package.

    (I tried to integrate points raised there into this issue, especially those by @JukkaL in this comment.)

    Advantages

    • Due to typeshed's tests, packages in typeshed will continue to work with the latests versions of mypy and pytype.
    • Basic level of consistency and standards due to review by typeshed maintainers.
    • Consistent naming scheme for third-party stubs packages, allowing users to just "pip install <guessed name>" and it will work when there are stubs.
    • Tooling (like tests) is easier to manage as it can remain part of the typeshed package.
    • Easier to contribute to stubs, since contributors don't need to learn the intricacies of multiple stubs projects.
    • No need to start a separate project just to distribute stubs for a new package.

    Issues

    • Workload issues for typeshed maintainers.
    • Typeshed maintainers will often not be familiar with the package for which pull requests are opened.
    • Publishing stubs takes longer due to the necessary reviews.

    Further Considerations

    What should the generated packages be called? @ethanhs's PEP 561 actually requires stubs-only package to be named <package>-stubs. typeshed could squat these names and release them (and remove the stubs) on the request of upstream maintainers. Alternatively, typeshed could add a common prefix or suffix (ts, typeshed) or in addition to or instead of the -stubs suffix. This would be in violation of PEP 561, so we'd need to get broader consensus to amend the PEP. My personal favorite would be <package>-ts.

    To guarantee a fairly quick turnaround on stubs, to minimize work for publishing stubs, and to prevent all third-party stub packages to be updated whenever a new typeshed version is released, stubs for a specific third-party package should be published automatically when it changes.

    Possible Implementation

    • Add a generic setup-tp.py to typeshed that takes its package name from the directory it's in and uses the current date and time as version number.
    • Amend the CI process for master only so that after a successful test run, for every third-party package that was changed since the last successful run, the following is done automatically:
      1. Copy setup-tp.py into the third-party module directory as setup.py.
      2. Build the package in that directory.
      3. Upload to pypi.
    project-discussion 
    opened by srittau 114
  • Run stubtest on stubs on different platforms

    Run stubtest on stubs on different platforms

    Open problems:

    • [ ] How to install deps on other platforms. brew works well on macos, but no idea how to use windows (I've never touched it since 2008)
    • [x] Listing platform specific packages. Which ones should we add?
    • [x] I still need to change daily.yml to do the same thing for all stubs
    • [x] How to test this? Not quite clear for now. I will need to tweak some values

    Refs https://github.com/python/typeshed/issues/8660

    opened by sobolevn 47
  • Type stubs for tqdm library

    Type stubs for tqdm library

    While tqdm is very popular, it is not only not typed, but strips the types of sequences it receives due to the way it works. This should resolve the issue for most users.

    An issue to add type hints to tqdm has been around since 2016, but hasn't seen any progress.

    opened by Gilthans 42
  • Added stubs for D3DShot

    Added stubs for D3DShot

    I've filled in the types as best as I could. But I might need help with a few things.

    1. ~~I am not sure how to deal with the placeholder _Pointer types yet. I think I may have to create new classes just to expose their methods when type-checking. Although I think this PR is probably acceptable keeping them as Incomplete for now.~~
    2. ~~I created a placeholder _Frame type. Is it possible to type the D3DShot class based on which backend it uses? Otherwise I have to keep casting the _Frames when using it:~~ Edit, doesn't matter because of https://github.com/python/typeshed/issues/5768 image
    3. ~~I don't know how to deal with import issues in the CI.~~ https://github.com/python/typeshed/issues/5768
    opened by Avasam 38
  • change getattr stubs to better type the default argument and return type

    change getattr stubs to better type the default argument and return type

    from @JelleZijlstra in gitter:

    I agree that getattr with a default should return the type of that default. Probably the three-argument version should return Union[Any, T] where T is the type of the default. Feel free to submit a PR or issue to typeshed to make that change.

    The motivation for this comes from an example like the following, which I encountered while at work:

    def foo(...) -> List[int]:
        ...
        o = ...
        return [
            getattr(o, "int_attribute", None),
            getattr(o, "another_int_attribute", None),
        ]
    

    mypy accepts this because the analyzed return type is List[Any], but that's not actually safe.

    However, we can actually know this is unsafe at analysis time, because the type of the default value to getattr should be available and incorporated into the analyzed type. That is, in this case, the analyzed type really ought to be List[Optional[Any]] or List[Union[Any, None]], and since I assume that Union[Any, None] != Any, this better type ought to result in a mypy error, as expected.

    (as a secondary note, apparently invariance and Any don't play as one would expect if Any were supposed to be top-type, but that's not what matters for this issue.)

    opened by neilvyas 35
  • Added initial rework of the concurrent.futures module

    Added initial rework of the concurrent.futures module

    Added most of the missing sections present in the concurrent.futures module for the process.pyi and thread.pyi files, related to #4641.

    I'm sure there are plenty of edits needed for formatting reasons (like using generic types or TypeVars) so please let me know what should be added/fixed!

    opened by HunterAP23 34
  • PEP 647 (TypeGuard) tracker

    PEP 647 (TypeGuard) tracker

    I'd like to start using TypeGuard in typeshed. Here's what we need:

    • [x] mypy
    • [x] pyright
    • [x] pytype (opened https://github.com/google/pytype/issues/916)
    • [x] pyre (opened https://github.com/facebook/pyre-check/issues/425)
    • [ ] PyCharm
    feature-tracker 
    opened by JelleZijlstra 33
  • Add `urllib3.contrib.socks`; improve `urllib3.connectionpool`

    Add `urllib3.contrib.socks`; improve `urllib3.connectionpool`

    This is required to address some re-exports in https://github.com/python/typeshed/pull/8439

    The source code is available here: https://github.com/urllib3/urllib3/blob/main/src/urllib3/contrib/socks.py

    opened by kkirsche 29
  • Make `weakref.finalize` generic per todo comment

    Make `weakref.finalize` generic per todo comment

    Fix #8437

    This merge request makes weakref.finalize generic:

    1. _P is the ParamSpec of the function. This is used in the __init__ function and the detach / peek calls, as described here
    2. _T1 is the captured object, which is used in the detach and peek returns
    3. _T2 is the captured return value of the func callable, which is re-used in the detach and peek methods.
    4. As _ is an unused bitbucket, change it from Any to object, as any object is accepted since it's an unused argument
    opened by kkirsche 29
  • refactor: Add missing types related to requests

    refactor: Add missing types related to requests

    This begins the processing of completing the requests package's stubs.

    I attempted to use stubtest locally to do the whole thing, but it doesn't seem to load the custom typeshed directory using this command:

    stubtest --custom-typeshed-dir /Users/kkirsche/git/python/typeshed requests
    

    I'm assuming this may have to do with having types-requests installed?

    1. Adds missing stubs for __version__.py: https://github.com/psf/requests/blob/main/requests/version.py
      • Removes the use of Any for these values
    2. Add missing type alias names as seen here: https://github.com/psf/requests/blob/main/requests/compat.py#L74-L79
    3. Adds missing atomic_open and resolve_proxies functions
      • atomic_open: https://github.com/psf/requests/blob/main/requests/utils.py#L295-L305
      • resolve_proxies: https://github.com/psf/requests/blob/main/requests/utils.py#L857-L881
    4. Add missing get method to LookupDict:
      • get: https://github.com/psf/requests/blob/main/requests/structures.py#L98-L99
    5. Adds missing help.py stubs
      • https://github.com/psf/requests/blob/main/requests/help.py
    opened by kkirsche 28
  • Many functions that accept Iterable should actually accept Iterable | SupportsGetItem

    Many functions that accept Iterable should actually accept Iterable | SupportsGetItem

    Many functions in stdlib that are documented to accept an "iterable" are annotated as Iterable[T]. This means the arguments must have __iter__. However, the actual functions don't require the arguments to have __iter__, they also work with arguments that have only __getitem__. That's because internally they use iter (in Python) or PySequence_Fast (in C).

    As the docs for both iter and PySequence_Fast functions show, these functions support two protocols for the argument: the "iterable" protocol (__iter__) and the "sequence" protocol (__getitem__).

    Example functions that have this bug right now:

    enumerate
    iter
    str.join
    bytes.__new__
    bytes.join
    

    For enumerate, a bug was actually filed on the mypy repo but in fact I believe this should be corrected in typeshed.

    Aside: for loops also similarly accept "iterables" that have only __getitem__, but that is implemented inside type checkers themselves. For now mypy still doesn't support it properly, but Pyright does.

    opened by matangover 28
  • `gdb-stubs` fixes

    `gdb-stubs` fixes

    This PR provides a few minor fixes to the gdb stubs.

    I've mainly referenced an unofficial mirror https://github.com/bminor/binutils-gdb/tree/gdb-12-branch in the commit notes, although when I checked these locally, I've used apt's distribution of gdb 12.1 (/usr/share/gdb/python/) for Ubuntu 22.04. The official git https://www.sourceware.org/gdb/current/ is less accessible when cross-checking.

    Symbols available in the built-in module _gdb (accessible when running Python through gdb) can be double-checked by running stubgen inside gdb (although the function/method signatures suffers the same issues as https://github.com/python/mypy/issues/14094).

    $ gdb --eval-command=python-interactive
    GNU gdb (Ubuntu 12.1-0ubuntu1~22.04) 12.1
      ...
    Type "apropos word" to search for commands related to "word".
    >>> import sys, mypy.stubgen
    >>> sys.argv = ["stubgen", "-m", "_gdb"]
    >>> mypy.stubgen.main()
    Processed 1 modules
    Generated out/_gdb.pyi
    
    opened by bzoracler 1
  • Offer sensible default VSCode settings

    Offer sensible default VSCode settings

    Offer sensible default VSCode settings. These are the workspace settings, specific to typeshed, that I've been using and filling in over the past few months. Workspace settings override user settings, so we can offer sensible, all-ready configurations for the typeshed workspace, reducing a lot of the pains a new contributor can have if their favorite editor is VSCode.

    These settings obviously won't configure any extension not specified in .vscode/extensions.json > recommendations, and will assume the user may not have all recommended extensions installed or set as the formatter. Hence I've also configure some basic VSCode settings.


    The recommended extensions include:

    • The full python extensions suite needed for typeshed
    • .editorconfig support and syntax highlighter
    • A yaml formatter and validator
    • A TOML syntax highliter and validator (no formatting)
    • Mardown pack for syntax highlighting, and for the Mardown preview to match Github's (no formatter, though I'd recommend davidanson.vscode-markdownlint) For those not familiar with VSCode: Note that recommendations are not forced onto the user, a popup appears once to mention the workspace has recommended extensions, then they'll only show up under the "recommended" tab in the extensions menu.

    It can still make sense for a user to want to modify .vscode/settings.json if they want to configure one of their extension to work properly with typeshed, without having to outright disable it for the workspace. It's also up to the dev to decide if they wanna follow these specific editor settings.

    Unfortunately, VSCode doesn't (yet) offer any way to have "workspace defaults" or "user-worspace settings", so offering defaults to copy is the best we can do at the moment. And is what I've seen done in other open-source projects.

    opened by Avasam 1
  • Support external-dependencies in pyright

    Support external-dependencies in pyright

    Extracted from #9374 Work towards #5768

    Support external (non-type) dependencies in pyright in the CI. This also adds a new reusable script that can be run from CLI to get a list of dependencies (similar to get_packages.py) and leverages the read_dependencies method added in #9382

    opened by Avasam 5
  • Re-enable NQA102

    Re-enable NQA102

    Dependent on https://github.com/PyCQA/flake8-pyi/pull/313 , but won't need a new version (read that PR description for details). Flake8-pyi will no longer be dependent on typeshed pre-emptively ignoring new positives.

    Just opening this PR now so that you can merge whenever it's ready.

    opened by Avasam 1
Owner
Python
Repositories related to the Python Programming language
Python
A static type analyzer for Python code

pytype - ? ✔ Pytype checks and infers types for your Python code - without requiring type annotations. Pytype can: Lint plain Python code, flagging c

Google 4k Dec 31, 2022
Optional static typing for Python 3 and 2 (PEP 484)

Mypy: Optional Static Typing for Python Got a question? Join us on Gitter! We don't have a mailing list; but we are always happy to answer questions o

Python 14.4k Jan 5, 2023
Static type checker for Python

Static type checker for Python Speed Pyright is a fast type checker meant for large Python source bases. It can run in a “watch” mode and performs fas

Microsoft 9.4k Jan 7, 2023
A static analysis tool for Python

pyanalyze Pyanalyze is a tool for programmatically detecting common mistakes in Python code, such as references to undefined variables and some catego

Quora 212 Jan 7, 2023
TidyPy is a tool that encapsulates a number of other static analysis tools and makes it easy to configure, execute, and review their results.

TidyPy Contents Overview Features Usage Docker Configuration Ignoring Issues Included Tools Included Reporters Included Integrations Extending TidyPy

Jason Simeone 33 Nov 27, 2022
Robocop is a tool that performs static code analysis of Robot Framework code.

Robocop Introduction Documentation Values Requirements Installation Usage Example Robotidy FAQ Watch our talk from RoboCon 2021 about Robocop and Robo

marketsquare 132 Dec 29, 2022
Pymwp is a tool for automatically performing static analysis on programs written in C

pymwp: MWP analysis in Python pymwp is a tool for automatically performing static analysis on programs written in C, inspired by "A Flow Calculus of m

Static Analyses of Program Flows: Types and Certificate for Complexity 2 Dec 2, 2022
CodeAnalysis - Static Code Analysis: a code comprehensive analysis platform

TCA, Tencent Cloud Code Analysis English | 简体中文 What is TCA Tencent Cloud Code A

Tencent 1.3k Jan 7, 2023
A simple stopwatch for measuring code performance with static typing.

A simple stopwatch for measuring code performance. This is a fork from python-stopwatch, which adds static typing and a few other things.

Rafael 2 Feb 18, 2022
A Python utility / library to sort imports.

Read Latest Documentation - Browse GitHub Code Repository isort your imports, so you don't have to. isort is a Python utility / library to sort import

Python Code Quality Authority 5.5k Jan 6, 2023
pycallgraph is a Python module that creates call graphs for Python programs.

Project Abandoned Many apologies. I've stopped maintaining this project due to personal time constraints. Blog post with more information. I'm happy t

gak 1.7k Jan 1, 2023
Turn your Python and Javascript code into DOT flowcharts

Notes from 2017 This is an older project which I am no longer working on. It was built before ES6 existed and before Python 3 had much usage. While it

Scott Rogowski 3k Jan 9, 2023
Inspects Python source files and provides information about type and location of classes, methods etc

prospector About Prospector is a tool to analyse Python code and output information about errors, potential problems, convention violations and comple

Python Code Quality Authority 1.7k Dec 31, 2022
Find dead Python code

Vulture - Find dead code Vulture finds unused code in Python programs. This is useful for cleaning up and finding errors in large code bases. If you r

Jendrik Seipp 2.4k Jan 3, 2023
Code audit tool for python.

Pylama Code audit tool for Python and JavaScript. Pylama wraps these tools: pycodestyle (formerly pep8) © 2012-2013, Florent Xicluna; pydocstyle (form

Kirill Klenov 966 Dec 29, 2022
The strictest and most opinionated python linter ever!

wemake-python-styleguide Welcome to the strictest and most opinionated python linter ever. wemake-python-styleguide is actually a flake8 plugin with s

wemake.services 2.1k Jan 5, 2023
The uncompromising Python code formatter

The Uncompromising Code Formatter “Any color you like.” Black is the uncompromising Python code formatter. By using it, you agree to cede control over

Python Software Foundation 30.7k Dec 28, 2022
A formatter for Python files

YAPF Introduction Most of the current formatters for Python --- e.g., autopep8, and pep8ify --- are made to remove lint errors from code. This has som

Google 13k Dec 31, 2022
Performant type-checking for python.

Pyre is a performant type checker for Python compliant with PEP 484. Pyre can analyze codebases with millions of lines of code incrementally – providi

Facebook 6.2k Jan 7, 2023