Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Generate function stubs from C module

I made a Python module in C/C++ with Python C API. I use setuptools.Extension in my setup.py.

It creates one .py file which loads a python module from some compiled .pyd file:

def __bootstrap__():
    global __bootstrap__, __loader__, __file__
    import sys, pkg_resources, imp
    __file__ = pkg_resources.resource_filename(__name__, 'zroya.cp36-win32.pyd')
    __loader__ = None; del __bootstrap__, __loader__
    imp.load_dynamic(__name__,__file__)
__bootstrap__()

But it does not generate python stubs for IDE autocomplete feature. I would like all exported functions and classes to be visible from .py file:

def myfunction_stub(*args, **kwargs):
    """
    ... function docstring
    """
    pass

Is it possible? Or do I have to create some python "preprocessor" which loads data from .pyd file and generate stubs with docstrings?

Source code is available on github.

like image 365
Lorin Avatar asked May 26 '26 05:05

Lorin


1 Answers

Unfortunately, mypy's stubgen does not (yet) include docstrings and signatures. However, it is relatively easy to automatically generate your own stub's using the Python native inspect package. For example, I use something along the lines of:

import my_package
import inspect

with open('my_package.pyi', 'w') as f:
    for name, obj in inspect.getmembers(nf):
        if inspect.isclass(obj):
            f.write('\n')
            f.write(f'class {name}:\n')

            for func_name, func in inspect.getmembers(obj):
                if not func_name.startswith('__'):
                    try:
                        f.write(f'    def {func_name} {inspect.signature(func)}:\n')
                    except:
                        f.write(f'    def {func_name} (self, *args, **kwargs):\n')
                    f.write(f"      '''{func.__doc__}'''")
                    f.write('\n    ...\n')

So essentially, first install your package and afterwards you can run this script to create a .pyi. You can change it easily to your liking! Note that you must correctly define docstrings in your C/C++ code: https://stackoverflow.com/a/41245451/4576519

like image 106
Thomas Wagenaar Avatar answered May 30 '26 06:05

Thomas Wagenaar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!