Simple `.pyi` stubs generator from thrift interfaces

unmade, updated 🕥 2022-12-12 18:01:46

======== Overview ========

.. start-badges

.. image:: :alt: Build Status :target:

.. image:: :alt: Coverage Status :target:

.. image:: :alt: Codacy Badge :target:

.. image:: :alt: Requirements Status :target:

.. image:: :alt: PyPI Package latest release :target:

.. image:: :alt: PyPI Wheel :target:

.. image:: :alt: Supported versions :target:

.. image:: :alt: MIT License :target:

.. end-badges

This is simple .pyi stubs generator from thrift interfaces. Motivation for this project is to have autocomplete and type checking for dynamically loaded thrift interfaces


.. code-block:: bash

pip install thrift-pyi


Sample usage:

.. code-block:: bash

$ thriftpyi example/interfaces --output example/app/interfaces

Additionally to generated stubs you might want to create that will load thrift interfaces, for example:

.. code-block:: python

from pathlib import Path
from types import ModuleType
from typing import Dict

import thriftpy2

_interfaces_path = Path("example/interfaces")
_interfaces: Dict[str, ModuleType] = {}

def __getattr__(name):
        return _interfaces[name]
    except KeyError:
        interface = thriftpy2.load(str(_interfaces_path.joinpath(f"{name}.thrift")))
        _interfaces[name] = interface
        return interface

To see more detailed example of usage refer to example app <>_


Python and thrift are very different at argument handling. For example in thrift the following will be correct declaration:

.. code-block:: thrift

struct TodoItem {
    1: required i32 id
    3: optional i32 type = 1
    2: required string text

In python, fields without default values cannot appear after fields with default values. Therefore by default all fields are optional with default to None. This is compliant to thriftpy2 <>_.

However, if you want more strict behaviour you can specify --strict-optional option. For the case above, the following stubs will be generated:

.. code-block:: python

from dataclasses import dataclass

class TodoItem:
    id: int
    type: int = 1
    text: str


To install pre-commit hooks::

pre-commit install

To run the all tests run::



0.5.0 2022-12-12 18:01:13

  • Support TTYPE.Binary

0.4.0 2022-08-29 20:27:54

  • Generate stubs using ast instead of Jinja
  • Unpin black and autoflake dependencies
  • Support python 3.9 and python 3.10

0.3.0 2022-01-22 21:40:52

  • Allow to instantiate exceptions with arguments(bug reported by @mjpizz)

0.2.1 2021-11-03 22:09:15

  • Fix bug when empty exceptions could generate invalid python (#27)

0.2.0 2020-10-29 10:30:51

Added TType.Binary support

v0.1.0 2019-05-28 20:11:31

  • Release stable version
  • Add py38 stage to test matrix in travis
Aleksei Maslakov
GitHub Repository

python3 thrift thriftpy2 poetry pyi python-stubs ast astunparse