constants.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. from __future__ import annotations
  5. import os
  6. import pathlib
  7. import platform
  8. import sys
  9. from datetime import datetime
  10. import astroid
  11. import platformdirs
  12. from pylint.__pkginfo__ import __version__
  13. from pylint.typing import MessageTypesFullName
  14. PY38_PLUS = sys.version_info[:2] >= (3, 8)
  15. PY39_PLUS = sys.version_info[:2] >= (3, 9)
  16. PY310_PLUS = sys.version_info[:2] >= (3, 10)
  17. IS_PYPY = platform.python_implementation() == "PyPy"
  18. PY_EXTS = (".py", ".pyc", ".pyo", ".pyw", ".so", ".dll")
  19. MSG_STATE_CONFIDENCE = 2
  20. _MSG_ORDER = "EWRCIF"
  21. MSG_STATE_SCOPE_CONFIG = 0
  22. MSG_STATE_SCOPE_MODULE = 1
  23. # The line/node distinction does not apply to fatal errors and reports.
  24. _SCOPE_EXEMPT = "FR"
  25. MSG_TYPES: dict[str, MessageTypesFullName] = {
  26. "I": "info",
  27. "C": "convention",
  28. "R": "refactor",
  29. "W": "warning",
  30. "E": "error",
  31. "F": "fatal",
  32. }
  33. MSG_TYPES_LONG: dict[str, str] = {v: k for k, v in MSG_TYPES.items()}
  34. MSG_TYPES_STATUS = {"I": 0, "C": 16, "R": 8, "W": 4, "E": 2, "F": 1}
  35. # You probably don't want to change the MAIN_CHECKER_NAME
  36. # This would affect rcfile generation and retro-compatibility
  37. # on all project using [MAIN] in their rcfile.
  38. MAIN_CHECKER_NAME = "main"
  39. USER_HOME = os.path.expanduser("~")
  40. # TODO: 3.0: Remove in 3.0 with all the surrounding code
  41. OLD_DEFAULT_PYLINT_HOME = ".pylint.d"
  42. DEFAULT_PYLINT_HOME = platformdirs.user_cache_dir("pylint")
  43. DEFAULT_IGNORE_LIST = ("CVS",)
  44. class WarningScope:
  45. LINE = "line-based-msg"
  46. NODE = "node-based-msg"
  47. full_version = f"""pylint {__version__}
  48. astroid {astroid.__version__}
  49. Python {sys.version}"""
  50. HUMAN_READABLE_TYPES = {
  51. "file": "file",
  52. "module": "module",
  53. "const": "constant",
  54. "class": "class",
  55. "function": "function",
  56. "method": "method",
  57. "attr": "attribute",
  58. "argument": "argument",
  59. "variable": "variable",
  60. "class_attribute": "class attribute",
  61. "class_const": "class constant",
  62. "inlinevar": "inline iteration",
  63. "typevar": "type variable",
  64. "typealias": "type alias",
  65. }
  66. # ignore some messages when emitting useless-suppression:
  67. # - cyclic-import: can show false positives due to incomplete context
  68. # - deprecated-{module, argument, class, method, decorator}:
  69. # can cause false positives for multi-interpreter projects
  70. # when linting with an interpreter on a lower python version
  71. INCOMPATIBLE_WITH_USELESS_SUPPRESSION = frozenset(
  72. [
  73. "R0401", # cyclic-import
  74. "W0402", # deprecated-module
  75. "W1505", # deprecated-method
  76. "W1511", # deprecated-argument
  77. "W1512", # deprecated-class
  78. "W1513", # deprecated-decorator
  79. "R0801", # duplicate-code
  80. ]
  81. )
  82. def _warn_about_old_home(pylint_home: pathlib.Path) -> None:
  83. """Warn users about the old pylint home being deprecated.
  84. The spam prevention mechanism is due to pylint being used in parallel by
  85. pre-commit, and the message being spammy in this context
  86. Also if you work with an old version of pylint that recreates the
  87. old pylint home, you can get the old message for a long time.
  88. """
  89. prefix_spam_prevention = "pylint_warned_about_old_cache_already"
  90. spam_prevention_file = pathlib.Path(pylint_home) / datetime.now().strftime(
  91. prefix_spam_prevention + "_%Y-%m-%d.temp"
  92. )
  93. old_home = pathlib.Path(USER_HOME) / OLD_DEFAULT_PYLINT_HOME
  94. if old_home.exists() and not spam_prevention_file.exists():
  95. print(
  96. f"PYLINTHOME is now '{pylint_home}' but obsolescent '{old_home}' is found; "
  97. "you can safely remove the latter",
  98. file=sys.stderr,
  99. )
  100. # Remove old spam prevention file
  101. if pylint_home.exists():
  102. for filename in pylint_home.iterdir():
  103. if prefix_spam_prevention in str(filename):
  104. try:
  105. os.remove(pylint_home / filename)
  106. except OSError: # pragma: no cover
  107. pass
  108. # Create spam prevention file for today
  109. try:
  110. pylint_home.mkdir(parents=True, exist_ok=True)
  111. with open(spam_prevention_file, "w", encoding="utf8") as f:
  112. f.write("")
  113. except Exception as exc: # pragma: no cover # pylint: disable=broad-except
  114. print(
  115. "Can't write the file that was supposed to "
  116. f"prevent 'pylint.d' deprecation spam in {pylint_home} because of {exc}."
  117. )
  118. def _get_pylint_home() -> str:
  119. """Return the pylint home."""
  120. if "PYLINTHOME" in os.environ:
  121. return os.environ["PYLINTHOME"]
  122. _warn_about_old_home(pathlib.Path(DEFAULT_PYLINT_HOME))
  123. return DEFAULT_PYLINT_HOME
  124. PYLINT_HOME = _get_pylint_home()
  125. TYPING_NORETURN = frozenset(
  126. (
  127. "typing.NoReturn",
  128. "typing_extensions.NoReturn",
  129. )
  130. )
  131. TYPING_NEVER = frozenset(
  132. (
  133. "typing.Never",
  134. "typing_extensions.Never",
  135. )
  136. )
  137. DUNDER_METHODS: dict[tuple[int, int], dict[str, str]] = {
  138. (0, 0): {
  139. "__init__": "Instantiate class directly",
  140. "__del__": "Use del keyword",
  141. "__repr__": "Use repr built-in function",
  142. "__str__": "Use str built-in function",
  143. "__bytes__": "Use bytes built-in function",
  144. "__format__": "Use format built-in function, format string method, or f-string",
  145. "__lt__": "Use < operator",
  146. "__le__": "Use <= operator",
  147. "__eq__": "Use == operator",
  148. "__ne__": "Use != operator",
  149. "__gt__": "Use > operator",
  150. "__ge__": "Use >= operator",
  151. "__hash__": "Use hash built-in function",
  152. "__bool__": "Use bool built-in function",
  153. "__getattr__": "Access attribute directly or use getattr built-in function",
  154. "__getattribute__": "Access attribute directly or use getattr built-in function",
  155. "__setattr__": "Set attribute directly or use setattr built-in function",
  156. "__delattr__": "Use del keyword",
  157. "__dir__": "Use dir built-in function",
  158. "__get__": "Use get method",
  159. "__set__": "Use set method",
  160. "__delete__": "Use del keyword",
  161. "__instancecheck__": "Use isinstance built-in function",
  162. "__subclasscheck__": "Use issubclass built-in function",
  163. "__call__": "Invoke instance directly",
  164. "__len__": "Use len built-in function",
  165. "__length_hint__": "Use length_hint method",
  166. "__getitem__": "Access item via subscript",
  167. "__setitem__": "Set item via subscript",
  168. "__delitem__": "Use del keyword",
  169. "__iter__": "Use iter built-in function",
  170. "__next__": "Use next built-in function",
  171. "__reversed__": "Use reversed built-in function",
  172. "__contains__": "Use in keyword",
  173. "__add__": "Use + operator",
  174. "__sub__": "Use - operator",
  175. "__mul__": "Use * operator",
  176. "__matmul__": "Use @ operator",
  177. "__truediv__": "Use / operator",
  178. "__floordiv__": "Use // operator",
  179. "__mod__": "Use % operator",
  180. "__divmod__": "Use divmod built-in function",
  181. "__pow__": "Use ** operator or pow built-in function",
  182. "__lshift__": "Use << operator",
  183. "__rshift__": "Use >> operator",
  184. "__and__": "Use & operator",
  185. "__xor__": "Use ^ operator",
  186. "__or__": "Use | operator",
  187. "__radd__": "Use + operator",
  188. "__rsub__": "Use - operator",
  189. "__rmul__": "Use * operator",
  190. "__rmatmul__": "Use @ operator",
  191. "__rtruediv__": "Use / operator",
  192. "__rfloordiv__": "Use // operator",
  193. "__rmod__": "Use % operator",
  194. "__rdivmod__": "Use divmod built-in function",
  195. "__rpow__": "Use ** operator or pow built-in function",
  196. "__rlshift__": "Use << operator",
  197. "__rrshift__": "Use >> operator",
  198. "__rand__": "Use & operator",
  199. "__rxor__": "Use ^ operator",
  200. "__ror__": "Use | operator",
  201. "__iadd__": "Use += operator",
  202. "__isub__": "Use -= operator",
  203. "__imul__": "Use *= operator",
  204. "__imatmul__": "Use @= operator",
  205. "__itruediv__": "Use /= operator",
  206. "__ifloordiv__": "Use //= operator",
  207. "__imod__": "Use %= operator",
  208. "__ipow__": "Use **= operator",
  209. "__ilshift__": "Use <<= operator",
  210. "__irshift__": "Use >>= operator",
  211. "__iand__": "Use &= operator",
  212. "__ixor__": "Use ^= operator",
  213. "__ior__": "Use |= operator",
  214. "__neg__": "Multiply by -1 instead",
  215. "__pos__": "Multiply by +1 instead",
  216. "__abs__": "Use abs built-in function",
  217. "__invert__": "Use ~ operator",
  218. "__complex__": "Use complex built-in function",
  219. "__int__": "Use int built-in function",
  220. "__float__": "Use float built-in function",
  221. "__round__": "Use round built-in function",
  222. "__trunc__": "Use math.trunc function",
  223. "__floor__": "Use math.floor function",
  224. "__ceil__": "Use math.ceil function",
  225. "__enter__": "Invoke context manager directly",
  226. "__aenter__": "Invoke context manager directly",
  227. "__copy__": "Use copy.copy function",
  228. "__deepcopy__": "Use copy.deepcopy function",
  229. "__fspath__": "Use os.fspath function instead",
  230. },
  231. (3, 10): {
  232. "__aiter__": "Use aiter built-in function",
  233. "__anext__": "Use anext built-in function",
  234. },
  235. }
  236. EXTRA_DUNDER_METHODS = [
  237. "__new__",
  238. "__subclasses__",
  239. "__init_subclass__",
  240. "__set_name__",
  241. "__class_getitem__",
  242. "__missing__",
  243. "__exit__",
  244. "__await__",
  245. "__aexit__",
  246. "__getnewargs_ex__",
  247. "__getnewargs__",
  248. "__getstate__",
  249. "__index__",
  250. "__setstate__",
  251. "__reduce__",
  252. "__reduce_ex__",
  253. "__post_init__", # part of `dataclasses` module
  254. ]
  255. DUNDER_PROPERTIES = [
  256. "__class__",
  257. "__dict__",
  258. "__doc__",
  259. "__format__",
  260. "__module__",
  261. "__sizeof__",
  262. "__subclasshook__",
  263. "__weakref__",
  264. ]