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

Handle nested class names in stubgen #632

Merged
merged 2 commits into from
Jul 24, 2024

Conversation

ryancahoon-zoox
Copy link
Contributor

@ryancahoon-zoox ryancahoon-zoox commented Jul 5, 2024

Correct stubgen's handling of nested types (e.g. a class defined inside another class).

Previously, stubgen generated import statements in the .pyi file which includes the outer type.

I fix this by testing that the module name in the generated import is a module by using importlib.util.find_spec. This is the approach recommended by the python docs: "If you need to find out if a module can be imported without actually doing the import, then you should use importlib.util.find_spec()."

If stubgen is not able to access the referenced module, the new functionality does have a graceful fall-back behavior: if none of the possible partitions of module_name and class_name result in a successful import, it will default to the previous behavior of assuming that just the last segment of the type name is the class name (and the rest is the module name).

This may add some performance overhead from needing to call importlib.util.find_spec on each referenced type, but I don't know of another way to handle this nested-type case, unless we rely only on some sort of naming convention to distinguish type names from module names.

A unit test for the nested-type case is included.

Closes #633

tests/test_typing.cpp Outdated Show resolved Hide resolved
@wjakob
Copy link
Owner

wjakob commented Jul 6, 2024

Looks good to me, just a minor comment.

@wjakob wjakob merged commit 3f28254 into wjakob:master Jul 24, 2024
24 checks passed
TaylorP pushed a commit to sideeffects/nanobind that referenced this pull request Aug 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG]: Stubgen does not produce correct import statements for nested class names
2 participants