MCPcopy Index your code
hub / github.com/python/cpython / _get_writer

Function _get_writer

Lib/xml/etree/ElementTree.py:750–797  ·  view source on GitHub ↗
(file_or_filename, encoding)

Source from the content-addressed store, hash-verified

748
749@contextlib.contextmanager
750def _get_writer(file_or_filename, encoding):
751 # returns text write method and release all resources after using
752 try:
753 write = file_or_filename.write
754 except AttributeError:
755 # file_or_filename is a file name
756 if encoding.lower() == "unicode":
757 encoding="utf-8"
758 with open(file_or_filename, "w", encoding=encoding,
759 errors="xmlcharrefreplace") as file:
760 yield file.write, encoding
761 else:
762 # file_or_filename is a file-like object
763 # encoding determines if it is a text or binary writer
764 if encoding.lower() == "unicode":
765 # use a text writer as is
766 yield write, getattr(file_or_filename, "encoding", None) or "utf-8"
767 else:
768 # wrap a binary writer with TextIOWrapper
769 with contextlib.ExitStack() as stack:
770 if isinstance(file_or_filename, io.BufferedIOBase):
771 file = file_or_filename
772 elif isinstance(file_or_filename, io.RawIOBase):
773 file = io.BufferedWriter(file_or_filename)
774 # Keep the original file open when the BufferedWriter is
775 # destroyed
776 stack.callback(file.detach)
777 else:
778 # This is to handle passed objects that aren't in the
779 # IOBase hierarchy, but just have a write method
780 file = io.BufferedIOBase()
781 file.writable = lambda: True
782 file.write = write
783 try:
784 # TextIOWrapper uses this methods to determine
785 # if BOM (for UTF-16, etc) should be added
786 file.seekable = file_or_filename.seekable
787 file.tell = file_or_filename.tell
788 except AttributeError:
789 pass
790 file = io.TextIOWrapper(file,
791 encoding=encoding,
792 errors="xmlcharrefreplace",
793 newline="\n")
794 # Keep the original file open when the TextIOWrapper is
795 # destroyed
796 stack.callback(file.detach)
797 yield file.write, encoding
798
799def _namespaces(elem, default_namespace=None):
800 # identify namespaces used in this tree

Callers 2

writeMethod · 0.85
write_tableFunction · 0.85

Calls 3

openFunction · 0.50
lowerMethod · 0.45
callbackMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…