Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

brain_attrs.py 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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/master/COPYING.LESSER
  3. """
  4. Astroid hook for the attrs library
  5. Without this hook pylint reports unsupported-assignment-operation
  6. for atrrs classes
  7. """
  8. import astroid
  9. from astroid import MANAGER
  10. ATTR_IB = 'attr.ib'
  11. def is_decorated_with_attrs(
  12. node, decorator_names=('attr.s', 'attr.attrs', 'attr.attributes')):
  13. """Return True if a decorated node has
  14. an attr decorator applied."""
  15. if not node.decorators:
  16. return False
  17. for decorator_attribute in node.decorators.nodes:
  18. if decorator_attribute.as_string() in decorator_names:
  19. return True
  20. return False
  21. def attr_attributes_transform(node):
  22. """Given that the ClassNode has an attr decorator,
  23. rewrite class attributes as instance attributes
  24. """
  25. # Astroid can't infer this attribute properly
  26. # Prevents https://github.com/PyCQA/pylint/issues/1884
  27. node.locals["__attrs_attrs__"] = [astroid.Unknown(parent=node.body)]
  28. for cdefbodynode in node.body:
  29. if not isinstance(cdefbodynode, astroid.Assign):
  30. continue
  31. if isinstance(cdefbodynode.value, astroid.Call):
  32. if cdefbodynode.value.func.as_string() != ATTR_IB:
  33. continue
  34. else:
  35. continue
  36. for target in cdefbodynode.targets:
  37. rhs_node = astroid.Unknown(
  38. lineno=cdefbodynode.lineno,
  39. col_offset=cdefbodynode.col_offset,
  40. parent=cdefbodynode
  41. )
  42. node.locals[target.name] = [rhs_node]
  43. MANAGER.register_transform(
  44. astroid.Class,
  45. attr_attributes_transform,
  46. is_decorated_with_attrs)