Repository navigation
CPython docs database for module items #3098
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| pub(crate) type Result = std::result::Result<Option<&'static str>, ()>; | ||
|
|
||
| pub(crate) fn try_read(path: &str) -> Result { | ||
| static DATABASE: once_cell::sync::OnceCell<std::collections::HashMap<String, Option<String>>> = | ||
| once_cell::sync::OnceCell::new(); | ||
| let db = DATABASE.get_or_init(|| { | ||
| let raw = include_str!("../docs.json"); | ||
| serde_json::from_str(raw).expect("docs.json must be a valid json file") | ||
| }); | ||
| let data = db.get(path).ok_or(())?; | ||
| Ok(data.as_ref().map(|s| s.as_str())) | ||
| } | ||
|
|
||
| pub(crate) fn try_module_item(module: &str, item: &str) -> Result { | ||
| try_read(&format!("{}.{}", module, item)) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod test { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn test_module_item() { | ||
| let doc = try_module_item("array", "_array_reconstructor").unwrap(); | ||
| assert!(doc.is_some()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,6 +13,7 @@ mod error; | |
| mod util; | ||
|
|
||
| mod compile_bytecode; | ||
| mod doc; | ||
| mod from_args; | ||
| mod pyclass; | ||
| mod pymodule; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import sys | ||
| import warnings | ||
| from pydoc import ModuleScanner | ||
|
|
||
|
|
||
| def scan_modules(): | ||
| """taken from the source code of help('modules') | ||
|
|
||
| https://github.com/python/cpython/blob/63298930fb531ba2bb4f23bc3b915dbf1e17e9e1/Lib/pydoc.py#L2178""" | ||
| modules = {} | ||
|
|
||
| def callback(path, modname, desc, modules=modules): | ||
| if modname and modname[-9:] == ".__init__": | ||
| modname = modname[:-9] + " (package)" | ||
| if modname.find(".") < 0: | ||
| modules[modname] = 1 | ||
|
|
||
| def onerror(modname): | ||
| callback(None, modname, None) | ||
|
|
||
| with warnings.catch_warnings(): | ||
| # ignore warnings from importing deprecated modules | ||
| warnings.simplefilter("ignore") | ||
| ModuleScanner().run(callback, onerror=onerror) | ||
| return list(modules.keys()) | ||
|
|
||
|
|
||
| def import_module(module_name): | ||
| import io | ||
| from contextlib import redirect_stdout | ||
| # Importing modules causes ('Constant String', 2, None, 4) and | ||
| # "Hello world!" to be printed to stdout. | ||
| f = io.StringIO() | ||
| with warnings.catch_warnings(), redirect_stdout(f): | ||
| # ignore warnings caused by importing deprecated modules | ||
| warnings.filterwarnings("ignore", category=DeprecationWarning) | ||
| try: | ||
| module = __import__(module_name) | ||
| except Exception as e: | ||
| return e | ||
| return module | ||
|
|
||
|
|
||
| def is_child(module, item): | ||
| import inspect | ||
| item_mod = inspect.getmodule(item) | ||
| return item_mod is module | ||
|
|
||
|
|
||
| def traverse(module, names, item): | ||
| import inspect | ||
| has_doc = inspect.ismodule(item) or inspect.isclass(item) or inspect.isbuiltin(item) | ||
| if has_doc and isinstance(item.__doc__, str): | ||
| yield names, item.__doc__ | ||
| attr_names = dir(item) | ||
| for name in attr_names: | ||
| if name in ['__class__', '__dict__', '__doc__', '__objclass__', '__name__', '__qualname__']: | ||
| continue | ||
| try: | ||
| attr = getattr(item, name) | ||
| except AttributeError: | ||
| assert name == '__abstractmethods__' | ||
| continue | ||
|
|
||
| if module is item and not is_child(module, attr): | ||
| continue | ||
|
|
||
| is_type_or_module = (type(attr) is type) or (type(attr) is type(__builtins__)) | ||
| new_names = names.copy() | ||
| new_names.append(name) | ||
|
|
||
| if item == attr: | ||
| pass | ||
| elif not inspect.ismodule(item) and inspect.ismodule(attr): | ||
| pass | ||
| elif is_type_or_module: | ||
| yield from traverse(module, new_names, attr) | ||
| elif callable(attr) or not issubclass(type(attr), type) or type(attr).__name__ in ('getset_descriptor', 'member_descriptor'): | ||
| if inspect.isbuiltin(attr): | ||
| yield new_names, attr.__doc__ | ||
| else: | ||
| assert False, (module, new_names, attr, type(attr).__name__) | ||
|
|
||
|
|
||
| def traverse_all(): | ||
| for module_name in scan_modules(): | ||
| if module_name in ('this', 'antigravity'): | ||
| continue | ||
| module = import_module(module_name) | ||
| if hasattr(module, '__cached__'): # python module | ||
| continue | ||
| yield from traverse(module, [module_name], module) | ||
|
|
||
|
|
||
| def docs(): | ||
| docs = {'.'.join(names): doc for names, doc in traverse_all()} | ||
| return docs | ||
|
|
||
| if __name__ == '__main__': | ||
| import json | ||
| print(json.dumps(docs(), indent=4, sort_keys=True)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since this only concerns the builtins, why not use
sys.builtin_module_nameshere?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried it but found
sys.bulitin_module_namesis not covering all the c modules. I didn't investigate well but I think it is more like pre-loaded module before import.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
huh, maybe that in combination with
sys.stdlib_module_namesthen (but that landed in3.10I believe.