Skip to content

Commit

Permalink
Don't try to parse Hy as Python in pydoc.getdoc
Browse files Browse the repository at this point in the history
  • Loading branch information
Kodiologist committed May 3, 2024
1 parent e03bc14 commit 851ba6d
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions NEWS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ New Features
Bug Fixes
------------------------------
* Tracebacks now point to the correct code in more cases.
* `help` should no longer crash when objects are missing docstrings.

0.28.0 (released 2024-01-05)
=============================
Expand Down
18 changes: 18 additions & 0 deletions hy/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,21 @@ def rewriting_unparse(ast_obj):
return true_unparse(ast_obj)

ast.unparse = rewriting_unparse


if True:
import pydoc, inspect, re
true_getdoc = pydoc.getdoc
if not PY3_9:
pydoc._getdoc = inspect.getdoc
def getdoc(object):
"""A monkey-patched `pydoc.getdoc` that tries to avoid calling
`inspect.getcomments` for an object defined in Hy code, which would try
to parse the Hy as Python. The implementation is based on Python
3.12.3's `getdoc`."""
result = pydoc._getdoc(object) or (
None
if inspect.getfile(object).endswith('.hy')
else inspect.getcomments(object))
return result and re.sub('^ *\n', '', result.rstrip()) or ''
pydoc.getdoc = getdoc
32 changes: 32 additions & 0 deletions tests/native_tests/other.hy
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
;; Tests miscellaneous features of the language not covered elsewhere

(import
textwrap [dedent]
typing [get-type-hints]
importlib
pydoc
pytest
hy.errors [HyLanguageError])

Expand Down Expand Up @@ -50,3 +53,32 @@
(setv annotations (get-type-hints AnnotationContainer))
(assert (= (get annotations "x") int))
(assert (= (get annotations "z") bool)))


(defn test-pydoc [tmp-path monkeypatch]
; https://github.com/hylang/hy/issues/2578

(monkeypatch.syspath-prepend tmp-path)

(.write-text (/ tmp-path "pydoc_py.py") (dedent #[[
class C1:
'C1 docstring'
# a comment
class C2:
pass]]))
(importlib.invalidate-caches)
(import pydoc-py)
(assert (= (pydoc.getdoc pydoc-py.C1) "C1 docstring"))
(assert (= (pydoc.getdoc pydoc-py.C2) "# a comment"))

(.write-text (/ tmp-path "pydoc_hy.hy") (dedent #[[
(defclass C1 []
"C1 docstring")
; a comment
(defclass C2)]]))
(importlib.invalidate-caches)
(import pydoc-hy)
(assert (= (pydoc.getdoc pydoc-hy.C1) "C1 docstring"))
(assert (= (pydoc.getdoc pydoc-hy.C2) "")))
; `pydoc` shouldn't try to get a comment from Hy code, since it
; doesn't know how to parse Hy.

0 comments on commit 851ba6d

Please sign in to comment.