brain_argparse.py 1.5 KB

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