1 import pydoc 2 from contextlib import suppress 3 from typing import Dict, Optional 4 5 from jedi.inference.names import AbstractArbitraryName 6 7 try: 8 from pydoc_data import topics 9 pydoc_topics: Optional[Dict[str, str]] = topics.topics 10 except ImportError: 11 # Python 3.6.8 embeddable does not have pydoc_data. 12 pydoc_topics = None 13 14 15 class KeywordName(AbstractArbitraryName): 16 api_type = 'keyword' 17 18 def py__doc__(self): 19 return imitate_pydoc(self.string_name) 20 21 22 def imitate_pydoc(string): 23 """ 24 It's not possible to get the pydoc's without starting the annoying pager 25 stuff. 26 """ 27 if pydoc_topics is None: 28 return '' 29 30 h = pydoc.help 31 with suppress(KeyError): 32 # try to access symbols 33 string = h.symbols[string] 34 string, _, related = string.partition(' ') 35 36 def get_target(s): 37 return h.topics.get(s, h.keywords.get(s)) 38 39 while isinstance(string, str): 40 string = get_target(string) 41 42 try: 43 # is a tuple now 44 label, related = string 45 except TypeError: 46 return '' 47 48 try: 49 return pydoc_topics[label].strip() if pydoc_topics else '' 50 except KeyError: 51 return '' 52