brain_argparse.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from astroid import arguments, inference_tip, nodes
  2. from astroid.exceptions import UseInferenceDefault
  3. from astroid.manager import AstroidManager
  4. def infer_namespace(node, context=None):
  5. callsite = arguments.CallSite.from_call(node, context=context)
  6. if not callsite.keyword_arguments:
  7. # Cannot make sense of it.
  8. raise UseInferenceDefault()
  9. class_node = nodes.ClassDef("Namespace", "docstring")
  10. class_node.parent = node.parent
  11. for attr in set(callsite.keyword_arguments):
  12. fake_node = nodes.EmptyNode()
  13. fake_node.parent = class_node
  14. fake_node.attrname = attr
  15. class_node.instance_attrs[attr] = [fake_node]
  16. return iter((class_node.instantiate_class(),))
  17. def _looks_like_namespace(node):
  18. func = node.func
  19. if isinstance(func, nodes.Attribute):
  20. return (
  21. func.attrname == "Namespace"
  22. and isinstance(func.expr, nodes.Name)
  23. and func.expr.name == "argparse"
  24. )
  25. return False
  26. AstroidManager().register_transform(
  27. nodes.Call, inference_tip(infer_namespace), _looks_like_namespace
  28. )