Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create __annotations__ for functions #305

Closed
konstin opened this issue Dec 8, 2018 · 3 comments
Closed

Create __annotations__ for functions #305

konstin opened this issue Dec 8, 2018 · 3 comments

Comments

@konstin
Copy link
Member

konstin commented Dec 8, 2018

In python 3, functions and methods can have an __annotations__ attribute, which is automatically initialized with type hints:

>>> def foo(a: str, b: int) -> str:
...    return a * b
>>> help(foo)
Help on function foo in module __main__:
foo(a:str, b:int) -> str
>>> foo.__annotations__
{'a': <class 'str'>, 'b': <class 'int'>, 'return': <class 'str'>}

Those annotations are used for ide type hints and can be used as basis for generating .pyi files. (iirc there is even a tool that can do that automatically)

Implementation

In the proc macros, we get the function argument types, but only as ast, not as resolved typed.
So first, implement a function we can call on all possible rust types for arguments (rust native, python native and custom) that returns the corresponding type object. Then generate code that builds a dict with the annotations using that function. During runtime, add that dict with PyFunction_SetAnnotations. Make sure to take of tyke possible cyclic dependencies (afaik this is done by using the string name instead the type object when there would otherwise be a cycle).

This could possibly even be extended to modules and class, s. datamodel.

@mehcode
Copy link

mehcode commented Dec 11, 2018

From what I understand PyFunction_SetAnnotations is totally illegal for extension modules. I hope I'm wrong though.

@ijl
Copy link
Contributor

ijl commented Dec 13, 2018

I tried PyFunction_SetAnnotations and indeed it failed. This is comprehensive: https://stackoverflow.com/a/50763175

@konstin
Copy link
Member Author

konstin commented Dec 15, 2018

Thanks for the link @ijl. With that I found the corresponding cpython bug: https://bugs.python.org/issue3208.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants