Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Preface: This is a terrible way to generate HTML, but if you're going to do it, you'd might as well do it the best way possible.</p> <p>One thing that python is exceptionally good at is string formatting. If you're concatting lots of tiny strings, you're killing your performance from the get-go. Your <code>to_string()</code> method should look more like this:</p> <pre><code>def to_string(self): return """&lt;{tag}{attributes}&gt;{content}&lt;/{tag}&gt;""".format( tag=self.tag, attributes=' '.join('%s="%s"' % (attr, val) for attr, val in self.attributes), content=''.join( (n if isinstance(n, basestring) else n.to_string()) for n in self.contents)) </code></pre> <p>Take note of a few things that I did there:</p> <ol> <li>This is Python, not Java. Stack frames are expensive, so minimize function and method calls.</li> <li>If you don't need a function to abstract a property, don't do it. I.e.: you don't need <code>attr_g</code> (except maybe to do escaping, but you can do that when you're putting the data in instead).</li> <li>Do all of your string formatting on the same string! Having a single string formatting operation for a tiny string and then yielding it to be concatted is a huge waste.</li> <li>Don't use a generator for this. Every time you yield, you're mussing around with the instruction pointer, which is going to inherently slow things down.</li> </ol> <p>Other pointers:</p> <ul> <li>You're inheriting from <code>object</code>, so use the <code>super()</code> function.</li> <li><p>Don't waste code by writing constructors to declare the tag type:</p> <pre><code>class TAG(object): def __init__(self, contents=None, **attributes): self.contents = contents self.attributes = attributes class H1(TAG): tag = 'H1' class H2(TAG): tag = 'H2' </code></pre></li> <li><p>You might have some success with <code>StringIO</code> objects if you're doing a lot of this. They'll let you build your tags and <code>.write()</code> them in. You can think of them as .Net <code>StringBuffer</code>s or Java's <code>StringBuilder</code>s.</p></li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload