keywords.py 1.2 KB

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