Brython - Python in the browser

Pierre Quentel pierre.quentel at gmail.com
Fri Dec 21 16:36:43 CET 2012


> Pythonic also means:
> If the implementation is hard to explain, it's a bad idea.
> What, exactly, does the sum of a string and a bolded string produce?  Can you explain that easily and clearly?

Yes : a+b returns the string a+str(b)

It is exactly what you get in CPython with 
>>> class B:
...   def __init__(self,value):
...     self.value = value
...   def __radd__(self,other):
...     return '%s<b>%s</b>' %(other,self.value)
...
>>> 'hello '+B('world')
'hello <b>world</b>'

> The DOM structure is, undeniably, quite verbose. But you could go for
> something with the same tree structure while a lot less wordy by
> simply returning self from lots of methods, thus allowing method
> chaining - something like this:
> 
> https://github.com/Rosuav/Gypsum/blob/master/window.pike#L247
> 
Hang me if I understand what this code is supposed to do ;-)
> 
> To produce the HTML code
> 
> <DIV>hello <B>world</B></DIV>
> 
> you might use:
> 
> doc.add(Tag('DIV').add('hello ').add(Tag('B').add('world')))
> 
No, with this syntax, the result of Tag('B').add('world') is below 'hello' in the tree structure, not at the same level (just below Tag('DIV')) as it should be

In this case it's not a real problem, but it's obvious if you want to produce <ul><li>one<li>two</ul> : you would need 2 different 'add'
top = Tag('UL')
top.add(Tag('LI').add('one'))
top.add(Tag('LI').add('two'))

With the syntax used in Brython : UL(LI('one')+LI('two'))


> 
> Reject the idea if you will, but do at least please consider it :)
> 
I did in fact consider many options before proposing this one. I have done a lot of web programming, including a web framework, and I faced the problem of generating HTML code from Python. I started with a syntax with nested parenthesis and chained methods returning self, only ending in ugly, unreadable code. Once I started using <= for "add child" and "+" for "add brother" (I first proposed it in the Python Cookbook recipe #366000, the HTMLTags module) - and I've used it on fairly large projects - the result was a much cleaner code



More information about the Python-list mailing list