brain_argparse.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  2. # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
  4. from __future__ import annotations
  5. from astroid import arguments, nodes
  6. from astroid.context import InferenceContext
  7. from astroid.exceptions import UseInferenceDefault
  8. from astroid.inference_tip import inference_tip
  9. from astroid.manager import AstroidManager
  10. def infer_namespace(node, context: InferenceContext | None = None):
  11. callsite = arguments.CallSite.from_call(node, context=context)
  12. if not callsite.keyword_arguments:
  13. # Cannot make sense of it.
  14. raise UseInferenceDefault()
  15. class_node = nodes.ClassDef(
  16. "Namespace",
  17. lineno=node.lineno,
  18. col_offset=node.col_offset,
  19. parent=nodes.SYNTHETIC_ROOT, # this class is not real
  20. end_lineno=node.end_lineno,
  21. end_col_offset=node.end_col_offset,
  22. )
  23. for attr in set(callsite.keyword_arguments):
  24. fake_node = nodes.EmptyNode()
  25. fake_node.parent = class_node
  26. fake_node.attrname = attr
  27. class_node.instance_attrs[attr] = [fake_node]
  28. return iter((class_node.instantiate_class(),))
  29. def _looks_like_namespace(node) -> bool:
  30. func = node.func
  31. if isinstance(func, nodes.Attribute):
  32. return (
  33. func.attrname == "Namespace"
  34. and isinstance(func.expr, nodes.Name)
  35. and func.expr.name == "argparse"
  36. )
  37. return False
  38. def register(manager: AstroidManager) -> None:
  39. manager.register_transform(
  40. nodes.Call, inference_tip(infer_namespace), _looks_like_namespace
  41. )