Create .pyi files automatically?

前端 未结 2 969
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 12:32

How can I automatically create the boilerplate code of pyi files?

I want to create a pyi file for type hinting as described in pep484 which contains all method names

相关标签:
2条回答
  • 2020-12-23 13:10

    I wrote a makefile for this:

    package := example
    sources := $(wildcard $(package)/*.py)
    
    stub: $(sources)
        stubgen --output . --package $(package)
    
    dist: setup.py stub
        python $< sdist bdist_wheel
    
    publish: dist
        twine upload dist/*
    
    .PHONY += stub dist publish
    

    Running make publish will generate the .pyi files in the same location as their corresponding .py files before packaging and uploading to PyPI. They will be included in the package provided that they are part of package_data.

    0 讨论(0)
  • 2020-12-23 13:14

    As far as I am concerned, there is no such direct tool in PyCharm. There are, however, 3rd party tools for this.


    .pyi generators

    MyPy

    Yes, I guess anyone who wants to use compile-time type checking in Python, probably ends up using MyPy. MyPy contains stubgen.py tool which generates .pyi files.

    Usage

    mkdir out
    stubgen urllib.parse
    

    generates out/urllib/parse.pyi.

    You can use it wit Python2 too:

    stubgen --py2 textwrap
    

    And for C modules:

    scripts/stubgen --docpath <DIR>/Python-3.4.2/Doc/library curses
    

    If you want to specify the path to your custom package, you can use --search-path option:

    stubgen my-pkg --search-path=folder/path/to/the/package
    

    make-stub-files

    This project is dedicated to exactly this goal.

    Usage

    A very basic one (but it has a handful of options, just consult README.md or make_stub_files -h

    make_stub_files foo.py
    

    pre-written .pyi files

    So you don't have to write your own.

    Typeshed

    Yes, if you're using .pyi files in your own project, you probably want to use this also when using external code. Typeshed contains .pyi files for Python2 and Python3 stdlib and a bunch of Python2 libraries (like redis, crypto, ...) and some Python3 libraries (like werkzeug or requests), all nicely versioned.


    PyCharm alternatives to .pyi files

    In case you're lazy, or simply just working on a project which doesn't require .pyi files and you don't want to be bothered by using 3rd party tools, PyCharm allows you to use:

    • Type docstrings (legacy)
    • Python 3 function annotations
    0 讨论(0)
提交回复
热议问题