Collection of library stubs for Python, with static types



Build status Chat at Pull Requests Welcome


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 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.


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.


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 for the coding style used in typeshed.

Directory structure


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.


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

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.


Please read 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/ tests typeshed with mypy
  • tests/ tests typeshed with pytype.
  • tests/ checks mypy's code base using this version of typeshed.
  • tests/ runs a subset of mypy's test suite using this version of typeshed.
  • tests/ checks certain files in typeshed remain consistent with each other.
  • tests/ checks stubs against the objects at runtime.
  • flake8 enforces a style guide.



$ 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.

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

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/

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

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

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/

This test works similarly to, except it uses pytype.

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

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

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

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.

Run using: python3 tests/

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

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 requires Python 3.6 or higher. Run using: (.venv3)$ flake8

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

  • 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.)


    • 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.


    • 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 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 into the third-party module directory as
      2. Build the package in that directory.
      3. Upload to pypi.
    opened by srittau 114
  • 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
    • [x] pyre (opened
    • [ ] PyCharm
    opened by JelleZijlstra 33
  • More complete type stubs for tkinter Canvas methods.

    More complete type stubs for tkinter Canvas methods.

    This change

    • Establishes a NewType called _ObjectId, meant to ensure that arbitrary handles aren't created.
    • Defines more specific method declarations for Canvas instances.
    opened by DanielRosenwasser 27
  • Symlinks don't work right on Windows

    Symlinks don't work right on Windows

    As noted in #1173, git does not support symlinks on Windows. This means that our use of symlinks in typeshed (admittedly pretty limited) is entirely broken on Windows, since a symlink just shows up as a plain text file on Windows whose contents is the name of the file to which it points.

    See for more info.

    AFAIK there are two ways out:

    1. Get rid of all symlinks in favor of copies -- but then there's the risk of divergence (e.g. between stdlib/3.4/enum.pyi and third_party/3/enum.pi).

    2. Write a post-checkout script that runs on Windows and detects symlinks and replaces them with the contents of the referenced file (see stackoverflow above for more details).

    Note that while this problem doesn't appear in current tests, it has caused AppVeyor tests to fail (e.g. and there are several files in the Windows-specific wheel files on PyPI that are indeed just little text files like described above.

    opened by gvanrossum 27
  • Return Union type for `List.__add__`

    Return Union type for `List.__add__`

    In Python, lists of union types are just common. We want to support easy construction of lists e.g.

    `[1, 2] + ['3']` or
    `['foo' if p else None, 'bar'] + ['zoo']`

    We adjust __iadd__ accordingly. Although returning a union here too looks strange, it has the effect that

    l = [1,2]
    l += ['3']  # ERR: Result type of + incompatible in assignment

    correctly fails.

    opened by kaste 26
  • Static and run-time tests for stubs

    Static and run-time tests for stubs

    Based on the discussion in #862 I propose a better way of testing stubs. The tests in this PR are a subject to both static checking by a type checker and run-time checking via pytest.

    The convention for testing your change to stub files:

    • Add pytest-compatible tests that use the API of the stub you're about to change
    • A test should pass the run-time pytest check
    • A test should statically fail with type errors before the change and pass after it
    • A third-party library test should pip install its precise dependencies as the first step
    opened by vlasovskikh 26
  • Rework socket

    Rework socket

    • Extract _socket.pyi from socket.pyi.
    • Extract _socket.socket from socket.socket.
    • Fix annotation.
    • Annotate SocketIO properly.
    • SocketType is an alias of _socket.socket.
    • Sort items in socket.pyi in the same order as in
    • Remove socket.EINTR.
    • Add socket.errorTab (Windows only) and _socket.dup().
    • Use _typeshed.WriteableBuffer instead of custom alias.
    • Use built-in generics.
    • Use socket.socket rather than socket.SocketType in stdlib and third-party stubs.
    opened by srittau 25
  • Stub for fractions

    Stub for fractions

    I was trying to create the stub for the Python 3.4 statistics module, but it depends on the fractions module. So here is my attempt for the fractions module, any suggestion accepted.

    opened by youtux 24
  • `subprocess.list2cmdline`: wrong type of the `seq` argument

    `subprocess.list2cmdline`: wrong type of the `seq` argument

    Problem description

    The code

    import subprocess
    from pathlib import Path
    from typing import Iterable, Union
    def test(command: Iterable[Union[str, Path]]) -> None:

    produces the error

    Mypy: Argument 1 to "list2cmdline" has incompatible type "Iterable[Union[str, Path]]"; expected "Iterable[str]"

    However, it works OK (tested with Python 3.9):

    >>> import subprocess
    ... from pathlib import Path
    >>> subprocess.list2cmdline(["foo", Path("bar")])
    'foo bar'

    Root cause

    The following stub is wrong:

    Possible solution

    According to the source code, the signature should be:

    def list2cmdline(seq: Iterable[Union[str, bytes, PathLike[str], PathLike[bytes]]]) -> str: ...  # undocumented 
    type-false-positive size-small good-first-issue 
    opened by AndreyMZ 1
  • Upgrade PyYAML to version 6

    Upgrade PyYAML to version 6


    opened by srittau 3
  • Adds `redis/commands.pyi`

    Adds `redis/commands.pyi`

    Generated using stubgen from master version of

    opened by sobolevn 6
  • Add stub file for xml/dom/

    Add stub file for xml/dom/

    I made a stab at adding stubs for xml/dom/ (cpython source code here). A little tricky, since documentation is rather thin on the ground, but perhaps an improvement on what's there at the moment?

    opened by AlexWaygood 7
  • Methods missing from importlib.machinery.ModuleSpec.loader()

    Methods missing from importlib.machinery.ModuleSpec.loader()

    The following code:

    from importlib.util import find_spec, module_from_spec
    spec = find_spec('A')
    assert spec
    module = module_from_spec(spec)
    assert spec.loader

    produces the following ouput:

    $ python3
    $ mypy error: "_LoaderProtocol" has no attribute "exec_module"  [attr-defined]
    Found 1 error in 1 file (checked 1 source file)
    $ mypy --version
    mypy 0.910
    $ python3 --version
    Python 3.8.10
    $ cat /etc/issue
    Ubuntu 20.04.3 LTS \n \l
    $ uname -a
    Linux ubuntu 5.4.0-88-generic #99-Ubuntu SMP Thu Sep 23 17:29:00 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

    I'm not sure how to fix this properly, as the current stubs for importlib.machinery.ModuleSpec are structured much differently than the code.

    opened by jolaf 2
  • Add a typeshed_utils package

    Add a typeshed_utils package

    Our tests as well as the stub_uploader contain quite a bit of duplication by now. The recent versions overhaul was fairly complicated and broke the stub_uploader for this reason. I think by now it makes sense to have common utility functions for:

    • METADATA parsing
    • VERSIONS parsing
    • Stub discovery
    • Third-party distributions handling

    This PR is a first stab at this that can certainly be improved and streamlined in later PRs.

    Previously discussed in #5673.

    Marking this as a draft for now for discussion. I can also split this into several PRs for easier reviewing.

    opened by srittau 10
  • subprocess stdout read1

    subprocess stdout read1

    import subprocess
    process = subprocess.Popen("echo hello", shell=True, stdout=subprocess.PIPE)
    assert process.stdout is not None

    mypy error: error: "IO[bytes]" has no attribute "read1"; maybe "read"?
    Found 1 error in 1 file (checked 1 source file)

    But at runtime there is read1() method. It is useful because unlike read(), it will return the output as soon as it is available, instead of reading more until it gets n bytes or end of file.

    opened by Akuli 0
  • Adds `TypeGuard` to `filter`

    Adds `TypeGuard` to `filter`

    Couple of questsions:

    1. How can I test that it works?

    I was testing it with local code:

    from typing import Iterator, Iterable, Callable, TypeVar, Generic, TypeGuard, Any, List, Optional, overload
    _T = TypeVar('_T')
    R = TypeVar('R')
    class filter(Iterator[_T], Generic[_T]):
        def __init__(self, __function: None, __iterable: Iterable[_T | None]) -> None: ...
        def __init__(self, __function: Callable[[R], TypeGuard[_T]], __iterable: Iterable[R]) -> None: ...
        def __init__(self, __function: Callable[[_T], Any], __iterable: Iterable[_T]) -> None: ...
        def __iter__(self) -> Iterator[_T]: ...
        def __next__(self) -> _T: ...
    a: List[Optional[int]]
    def is_int_typeguard(a: object) -> TypeGuard[int]: pass
    cc = filter(is_int_typeguard, a)
    reveal_type(cc)  # N: Revealed type is "ex.filter[Union[, None]]"
    1. This is the first TypeGuard in builtins.pyi, are there any extra steps?


    opened by sobolevn 6
  • `logging.LogRecord` does not have a `message` attribute

    `logging.LogRecord` does not have a `message` attribute

    The stub for LogRecord includes both the msg and message attributes but message is actually added as a side effect of logging.Formatter.format.

    I just ran into this today when writing a log filter and it surprised me. I should be able to put together a PR for this but I wanted to make sure that it was flagged as an issue.

    opened by dave-shawley 4
  • `logging.dictConfig` to accept `TypedDict` as an argument

    `logging.dictConfig` to accept `TypedDict` as an argument

    Currently dictConfig accepts Dict[str, Any] as an argument.

    But, there's a clearly defined schema for its argument. Docs:

    Maybe we can try to support it? It is really easy to mess things up in this long and nested dict. The only downside is that dictConfig() might not accept some valid dicts with statically unknown shape.

    opened by sobolevn 1
Repositories related to the Python Programming language
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 7.3k Oct 23, 2021
Typing-toolbox for Python 3 _and_ 2.7 w.r.t. PEP 484.

Welcome to the pytypes project pytypes is a typing toolbox w.r.t. PEP 484 (PEP 526 on the road map, later also 544 if it gets accepted). Its main feat

Stefan Richthofer 160 Oct 19, 2021
A system for Python that generates static type annotations by collecting runtime types

MonkeyType MonkeyType collects runtime types of function arguments and return values, and can automatically generate stub files or even add draft type

Instagram 3.5k Oct 18, 2021
🦔 PostHog is developer-friendly, open-source product analytics.

PostHog provides open-source product analytics, built for developers. Automate the collection of every event on your website or app, with no need to send data to 3rd parties. With just 1 click you can deploy on your own infrastructure, having full API/SQL access to the underlying data.

PostHog 4.8k Oct 24, 2021
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 142 Oct 15, 2021
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 11.6k Oct 25, 2021
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 29 Oct 17, 2021
Auto-generate PEP-484 annotations

PyAnnotate: Auto-generate PEP-484 annotations Insert annotations into your source code based on call arguments and return types observed at runtime. F

Dropbox 1.2k Oct 25, 2021
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 3.5k Oct 22, 2021
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 23.3k Oct 23, 2021
Typical: Fast, simple, & correct data-validation using Python 3 typing.

typical: Python's Typing Toolkit Introduction Typical is a library devoted to runtime analysis, inference, validation, and enforcement of Python types

Sean 131 Oct 15, 2021
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 4.2k Oct 25, 2021
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 1.9k Oct 23, 2021
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 5.6k Oct 23, 2021
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 1.7k Oct 23, 2021
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 817 Oct 14, 2021
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.6k Oct 20, 2021
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 12.1k Oct 25, 2021
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.5k Oct 22, 2021