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_io.py 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # Copyright (c) 2016 Claudiu Popa <pcmanticore@gmail.com>
  2. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  3. # For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
  4. '''Astroid brain hints for some of the _io C objects.'''
  5. import astroid
  6. BUFFERED = {'BufferedWriter', 'BufferedReader'}
  7. TextIOWrapper = 'TextIOWrapper'
  8. FileIO = 'FileIO'
  9. BufferedWriter = 'BufferedWriter'
  10. def _generic_io_transform(node, name, cls):
  11. '''Transform the given name, by adding the given *class* as a member of the node.'''
  12. io_module = astroid.MANAGER.ast_from_module_name('_io')
  13. attribute_object = io_module[cls]
  14. instance = attribute_object.instantiate_class()
  15. node.locals[name] = [instance]
  16. def _transform_text_io_wrapper(node):
  17. # This is not always correct, since it can vary with the type of the descriptor,
  18. # being stdout, stderr or stdin. But we cannot get access to the name of the
  19. # stream, which is why we are using the BufferedWriter class as a default
  20. # value
  21. return _generic_io_transform(node, name='buffer', cls=BufferedWriter)
  22. def _transform_buffered(node):
  23. return _generic_io_transform(node, name='raw', cls=FileIO)
  24. astroid.MANAGER.register_transform(astroid.ClassDef,
  25. _transform_buffered,
  26. lambda node: node.name in BUFFERED)
  27. astroid.MANAGER.register_transform(astroid.ClassDef,
  28. _transform_text_io_wrapper,
  29. lambda node: node.name == TextIOWrapper)