Handle nested class names in stubgen #632
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Correct
stubgen
's handling of nested types (e.g. a class defined inside another class).Previously,
stubgen
generatedimport
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 usingimportlib.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 useimportlib.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