Search code examples
pythonmagic-methods

Dynamic overwriting magic methods in python


I am looking for proper solution for this code I've made. I just want to have possibility to print my XML while it's still building.

from xml.dom.minidom import Document, DOMImplementation

class MyClass(object):

init():
    pass

def create_xml():
  doc = Document()
  # I know i cannot do that, I know. I need proper solution for that
  doc.__str__ = self.print_doc

def print_doc(document):
    return document.toprettyxml(encoding='UTF-8')

We're able to figure out a not clean way for it, that works, so you can see my idea here:

from xml.dom.minidom import Document, DOMImplementation

def create_xml():
  doc = Document()
  document.__str__ = partial(self.print_doc, document=document)

def print_doc(document):
    return document.toprettyxml(encoding='UTF-8')

My class needs to be static, as software cannot handle more, than one instance during whole run, still user has to create more than one xml during that run (yes, this is messed up, but that i cannot help). Instead making weird things, I did smth that will work for me:

class Child(Document):
   def __str__(self):
      return document.toprettyxml(encoding='UTF-8')

...so this class allows me to print

class MyClass(object):

def create_xml():
  return Document()

...all that, beacause i have to have

def main():
    xml = MyClass.create()
    print(xml)

...instead just

xml = Document()

Sorry everyone for confusing... i guess planing here is what i messed up first


Solution

  • Why not just subclass Document?

    class MyDoc(Document):
        def __str__(self):
            return self.toprettyxml(encoding='UTF-8')
    

    You can also create a wrapper class:

    class DocumentWrapper(object):
        def __init__(self, doc):
            self.doc = doc  # doc should be a "Document".
        def __str__(self):
            return self.doc.toprettyxml(encoding='UTF-8')