-
Notifications
You must be signed in to change notification settings - Fork 14
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
python: Generate/write (basic) type stubs #184
Comments
Managed to put this together pretty quickly, as a from __future__ import annotations
import inspect
import operator
from functools import partial
from types import ModuleType
from typing import Any, Iterator
import vl_convert as vlc
def predicate_module_member(member: Any, /, module: ModuleType) -> bool:
if name := getattr(member, "__name__", None):
return name in module.__all__
else:
return False
def extract_members(module: ModuleType, /) -> Iterator[tuple[str, inspect.Signature]]:
for name, member in sorted(
inspect.getmembers(module, partial(predicate_module_member, module=module)),
key=operator.itemgetter(0),
):
yield name, inspect.signature(member)
def format_member(name: str, signature: inspect.Signature, /) -> str:
if not signature.parameters:
return f"def {name}() -> Any: ..."
params = ", ".join(f"{p}: Any" for p in signature.parameters)
return f"def {name}({params}) -> Any: ..."
def generate_stub(module: ModuleType, /) -> str:
_imports = ("from typing import Any",)
imports = "\n".join(_imports)
contents = "\n".join(starmap(format_member, extract_members(module)))
return f"{imports}\n\n" f"__all__ = {module.__all__!r}\n\n" f"{contents}"
print(generate_stub(vlc)) Which after running the output through
|
Thanks for looking into this, I think I'd prefer to follow the If you do not have other Python files paradigm, and maintain a hand-written stub file at But what you generated here is a great starting point, and then we can refine the types of the function args over time. How does that sound? |
Sounds good to me! After working through #184 (comment) it seems like there is a lot of overlap between the signatures, so a hand-written stub should be easy to maintain. Another benefit there would be that including docstrings and accurate typing is only one extra (small) manual job to do in addition. I'm more than happy to do that today, if you'd like? |
Sure! |
Phew |
Using
vl_convert
in anipython
environment a full listing of the API available - including full signatures and docs.Sadly this isn't the case in a static environment, which leads to false positives from a type checker like the below.
https://github.com/vega/altair/blob/aeb0c721cce0c8099e0688d7f83beae2e0fa103d/tools/generate_schema_wrapper.py#L376
Screenshot
PyO3
seems to have some degree of support, not sure how complex it would be to implementFYI, I'm less interested in the types and moreso the names of functions/parameters
The text was updated successfully, but these errors were encountered: