6 ms·
Brython, Python in the browser
- aidos 14y agoThis was posted a couple of months ago - discussion here: http://news.ycombinator.com/item?id=4923530 http://news.ycombinator.com/item?id=4923530
- willvarfar 14y agoIt actually translates Python into Javascript! I'm thoroughly impressed. Another approach that may work in Chrome is to use Chrome Native Client to embed a 'proper' Python runtime. I've often lamented that we have Javascript and not Python :( http://williamedwardscoder.tumblr.com/post/20771096806/why-didnt-we-use-python-in-the-browser http://williamedwardscoder.tumblr.com/post/20771096806/why-d...
- cookiecaper 14y agoCompletely agree that Python ought to be the default browser scripting language. Far, far better than JS. I've always been excited about the prospect of NaCl because it may be able to help us make that a reality in some limited contexts.
- louischatriot 14y agoPython noob here, I am very interested in what you think makes Python a better browser scripting language than JS (which I use a lot on client and server side and like very much).
- willvarfar 14y agoIt is surely subjective. Not the person you reply to but I'll chip in anyway. I write lots of Javascript; mostly 'raw' Javascript in the webGL space. Here's just of the top of my head what's wrong with Javascript: * looping over elements has too much boilerplate * the mindfulnesss of 'this' is distracting * the duality of dictionaries and lists and how that's an easy lie to fall for is fustrating * that there are multiple frameworks trying to use $ On the other hand, their anonymous functions are very nice. And, I rather like prototypes vs classes. A bit. Sometimes With Python, I like significant whitespace (so sue me) and especially the syntax for collections and packing/unpacking them. I've blogged along these lines a lot in the past e.g. http://williamedwardscoder.tumblr.com/post/18319031919/programming-language-readability http://williamedwardscoder.tumblr.com/post/18319031919/progr...
- jashkenas 14y agoWith that particular list of features and complaints, you may want to take a quick look at CoffeeScript. It addresses everything on the list except for the "multiple frameworks trying to use $" bit.
- acjohnson55 14y agoI think the $ point is a bit soft anyway. With jQuery, it's easy enough to just use non-conflict mode.
- sim0n 14y agoIt's not often you want to use two libraries that both use $ anyway (e.g. you'd use jQuery OR prototype, Zepto OR MooTools - not usually both).
- willvarfar 14y agoFunnily enough, it was trying to use a box2d port that used prototype in an app that already used jquery that raised my hackles most recently...
- arnarbi 14y agoBoth languages are very good. JavaScript has its kinks, but they are not hard to work around with library support or syntax translations (such as CoffeeScript). However, JavaScript's execution model is simple and doesn't provide as much value as the one in Python does, and this is something that is not easily addressed with libraries or (simple) translations. By this I refer to that in Python, most syntactic constructs map to more primitive operations that are accessible (and overridable) in the language itself. For example, anything can be made callable, indexable, sliceable, iterable, etc., by providing the right interface. It is like operator overloading on steroids. Even attribute access (the dot operator) can be overridden in extremely powerful ways. This is great for library writers, who can use it to provide the simplest possible API to their users. I also like very much Python's data model. Things consistently behave as references (even primitive values which all behave as immutable singletons, although of course they are not implemented as such). It just somehow fits and makes sense once you have the model in your mind. JavaScript is slightly less intuitive in this way, and while it makes sense once you understand it, there are a few caveats you need to keep in mind (variable hoisting, scoping, anticipating different context objects). Prototype inheritance works fine but requires a special mind-set, and to me it seems JS fits better for functional programming than object-oriented Java-style. Python's shortcomings are mainly syntactical (not counting the shortcomings of CPython's implementation specifically), such as not having an easy syntax for function expressions. This is the main reason functional programming can get slightly awkward in Python.
- quarterto 14y agoES6 will allow for low-level extensibility with Proxies (http://wiki.ecmascript.org/doku.php?id=harmony:proxies http://wiki.ecmascript.org/doku.php?id=harmony:proxies).
- arnarbi 14y agoThat's true, and definitely worth pointing out. I've used them a fair bit, and while they provide exellent power, they are slightly cumbersome to use compared to Python's pervasive "overloadability" (for the lack of a better word). But I would give them a chance to grow on me before passing any further judgement.
- kmfrk 14y agoI get the impression from the above that Python is easier to learn and read, which I agree with. How well it'd work beyond that by comparison, I'm not sure.
- cookiecaper 14y agoI just really, really prefer Python and think it would greatly simplify the whole process, make scripts much, much easier to read, write and modify, etc. It's basically an argument that JavaScript is bad. Not sure what the deal is with the cult of JavaScript that's been arising in the last few years but in my mind it's still Brendan Eich's quick "seven days to save the company" hack, and for that it's impressive, but it should have been deprecated a long, long time ago. To be honest I'm not intimate enough with JS to give a big list of my biggest language-level annoyances off the top of my head. It's just a general distaste/annoyance that occurs every time I get involved in JavaScript code, either the reading or the writing of it. Python, on the other hand, is nearly readable by non-programmers, and is otherwise super cool. I recognize that others may have a different opinion on this than I have and while they're not necessarily wrong for themselves, I believe Python is more accessible in general. I think the facts that a) almost no one writes bare in-browser JavaScript anymore, it's all through jQuery and b) CoffeeScript and other persistent "rewrite/simplify/improve JS" movements exist and keep coming up are ample evidence that the basic tools provided by the browser and the JS language are insufficient.
- acjohnson55 14y agoThis more or less sums up what I despise about JS: http://bonsaiden.github.com/JavaScript-Garden/#intro http://bonsaiden.github.com/JavaScript-Garden/#intro. Python has way better language design. CoffeeScript may be better suited than Python though, because the callback-heavy nature of web programming is easier to tolerate when you have inline function literals and stuff, in my opinion.
- mdellavo 14y agoI love python but I'm not convinced that a language with significant whitespace is ideal for the web where formatting is too easily lost.
- lambda 14y agoHow is formatting "easily lost" merely by virtue of being used as a web scripting language? There's nothing that mangles whitespace of anything delivered over HTTP. Yes, if you include it directly in HTML for display without any kind of escaping, the whitespace will be collapsed. But if you'll notice, JavaScript is the current web scripting language, and it has significant whitespace (line endings). So it's not like having significant whitespace makes it unsuitable for the web.
- Scriptor 14y agoJavascript is frequently stripped of all whitespace as part of the minification process. This includes removing all newlines and indentation. This would a good bit harder with Python.
- cookiecaper 14y agoYes, they'd have to come up with something else to get equivalent results from minification, like a special minified dialect where whitespace characters are replaced with another unused symbol (perhaps a canary-type header like the coding: thing). If this is determined infeasible they'd probably just have to accept that the whitespace needs to be transferred, which honestly I wouldn't really consider a bad thing. Minification should not be considered as a major reason to forgo the benefits of alternate scripting languages.
- agumonkey 14y agoThe answer lies in between, ES6 borrows from python (as many other languages). I personally would love a coffeescript~ to be the one.
- pcwalton 14y agoNaCl is not needed for that. Embedding CPython into the browser has been done for some time now with Emscripten. Here's a demo: http://syntensity.com/static/python.html http://syntensity.com/static/python.html This has the advantage over NaCl that it works in all browsers, not just Chrome. It's also portable.
- willvarfar 14y agoThe point of a NaCL VM would be its speed. It could actually be PyPy or something, for real. Embedded just like the Flash or Java Applet runtime (in the NaCL container, which we have rather better security salts [pun] about.
- limitlessbooks 14y agoHow is the performance impacted? I could see myself using this for a SaaS app I am developing right now; would be useful to run the same language on the client as on the backend. But it needs to performant in this case.
- StavrosK 14y agoHow do these things happen? One moment, I know nothing about a lightweight Python interpreter in JS (a thing I would have heard about, even if it were in its infancy), and I see a full-blown interpretation the next. I'm amazed at how this has slipped past me so far. Does anyone know the specifics on how it works (performance, does it implement the complete language, etc)?
- friendly_chap 14y agoCompared to the original JS demo (linked on page), the version transpiled from python looks really choppy.
- leke 14y agoI think I prefer the Google/Dart approach -- that is, a language designed for the web browser and that has a native engine for the browser (although only currently included in chrome).
- thomasrambaud 14y agoI find it a bit the overkill. If you'd like to implement Python in the browser, at least make sure to write a good implementation. An implementation written in JavaScript, is not a good implementation.
- arnarbi 14y ago> An implementation written in JavaScript, is not a good implementation. Do you have some evidence for this, or are you just judging it by the fact it is written in JavaScript? I can imagine source-to-source translation between Python to JS that would provide an excellent implementation of Python.
- lemcoe9 14y agoHe should call it pQuery!
- draegtun 14y agoAlready taken! - http://www.pquery.org/ http://www.pquery.org/ Also see: http://ajaxian.com/archives/pquery-php-and-jquery http://ajaxian.com/archives/pquery-php-and-jquery | https://metacpan.org/release/pQuery https://metacpan.org/release/pQuery
- _ZeD_ 14y agoand pyQuery too - http://pypi.python.org/pypi/pyquery http://pypi.python.org/pypi/pyquery (btw it's a really good way to handle xml)
- omershapira 14y agoWonderful. Now give it a name that doesn't sound like "Bro-Python" and I'm sold.
- jarek-foksa 14y agoI don't like the fact that underscore and camelCase notations must be mixed, e.g. in the clock demo: def set_clock(): ctx.beginPath() ctx.fillStyle = "#FFF" ctx.arc(width/2,height/2,ray*0.89,0,2*math.pi) ctx.fill() show_hours() This is not the case with some other languages that compile to JavaScript, e.g. LiveScript allows dash-case almost everywhere.
- peller 14y agoThey don't; it's purely a matter of convention that Python style guides prefer under_scored over camelCased. But you are entirely free to implement all of your python functions and variables and whatnot in camelCase, and in fact, many libraries do.
- peller 14y agoYou could probably even try to write a decorator that converted under_scores function names to camelCase for a nice little introduction into various parts of some of the more internal pieces of python.
- _ZeD_ 14y agouhmm, AFAIK pep8 suggest UpperCamelCase for classes, under_score for packages, methods and functions[0] btw: it's not a decorator :) but a camelCase->under_score renamer it's pretty easy to write import re def unCamel(obj, *maybe_camels): if not maybe_camels: maybe_camels = filter(lambda n: not n.startswith('_'), dir(obj)) for maybe_camel in maybe_camels: underscore = re.sub(r'([^A-Z])([A-Z])([^A-Z])', lambda m: '%c_%c%c' % (m.group(1), m.group(2).lower(), m.group(3)), maybe_camel) if underscore != maybe_camel: setattr(obj, underscore, getattr(obj, maybe_camel)) if __name__ == '__main__': class CamelCase(object): def multiWordMethod(self): print('called multiWordMethod') def multiWordFunction(): print('called multiWordFunction') unCamel(CamelCase) # magic import sys unCamel(sys.modules[__name__], 'multiWordFunction') # magic CamelCase().multi_word_method() multi_word_function() [0] http://www.python.org/dev/peps/pep-0008/ http://www.python.org/dev/peps/pep-0008/
- denzil_correa 14y agoLooking for something like this since a long time now. Essentially, you have made a Google Web Toolkit (GWT) for Python. Good work, I hope it matures to a level and is widely adopted. Best luck!
- okhan 14y agoGWT was actually ported to python a while back. The project lives on at pyjs.org
- tsahyt 14y agoBrilliant. Now let it run natively in the browser rather than compiling to JS and you made the world a better place!
- tferris 14y agoI am impressed but I'm also wondering why people try to avoid learning new stuff -- to potential downvoters, no rant intended. I am just surprised how many people try to circumvent JS: Rubyists with Coffee, Closurists with ClosureScript, etc. instead of just using JS directly. I don't believe the main motivation is JS' potential inferiority and that you could employ much better design pattern with languages compiling to JS. Neither, JS' syntax is bad or ugly. I assume that's it's the fear of learning something new, to be again a beginner. JS has its quirks but in general it's a very modern and beautiful language and offering more innovation than traditional scripting languages. And V8 is so blazingly fast that I sometimes think this feels more like C compiled code which would be just another reason rather to switch to JS in the backend.
- lucian1900 14y agoIt's two things: 1. Sharing code between server and client 2. JavaScript sucks, badly. Many people would really much rather not have to deal with its many, many flaws.
- eric_bullington 14y agoI can't speak to ClojureScript, but in my experience, CoffeeScript is primarily used by people who already know JavaScript. You can't use CoffeeScript effectively without understanding JavaScript. Most of us who use CoffeeScript instead of JavaScript appreciate CoffeeScript's syntactic shortcuts, which for us makes it quicker to write and improvise with new ideas, as well as its enforced whitespace, which makes it easier to write maintainable code. Otherwise, as someone whose first and second strongest languages are Python and Javascript, I agree with you. JavaScript is a beautiful language that accommodates a variety of programming styles. As you mention, JavaScript is also much more performant than Python, which makes me questions whether Python would ever be a viable replacement for JavaScript in the browser. Add to that JavaScript's excellent webworker API compared to Python's choices for parallel programming. Now, Lua, on the other hand, would be an excellent browser language (specifically the LuaJit implementation). Lua is close enough to JavaScript that folks could easily pick it up, and its blazing fast. But it will never happen. Besides, there are so many great JS libraries now that in most cases, I wouldn't want to switch to Lua in the browser and face re-inventing the wheel (same reason why I generally use Python instead of Lua elsewhere). But its fun to think about.
- pizu 14y agoPlease upvote it you need Brython for Ruby!
- azakai 14y agohttp://qiezi.me/projects/mruby-web-irb/mruby.html http://qiezi.me/projects/mruby-web-irb/mruby.html
- Tekker 14y agoIs this just a translator Python->Javascript (which I would expect would have many holes in it) or is it being run by a true Python engine? And if it's run by a true Python engine, does the user have to have Python installed do run it? (Hard for me to tell since all my machines ATM have Python installed).
- gejjaxxita 14y agoIt's a translator and I agree it would probably have many holes in it. Also can you imagine importing libraries?
- lucian1900 14y agoThis isn't a particularly good implementation, though. Looking through the code, it's not something I'd be comfortable using. Skulpt is much better, and about as incomplete.
- dbaupp 14y agoThis was posted previously at https://news.ycombinator.com/item?id=4923530 https://news.ycombinator.com/item?id=4923530, along with some fairly extensive discussion and criticism. The basic gist of the criticism seems to be the code is basically just directly translating a Python token list (not an AST) into Javascript, and as such is reasonably fragile and horrible code (the main translator function: https://code.google.com/p/brython/source/browse/trunk/py2js.js#52 https://code.google.com/p/brython/source/browse/trunk/py2js.... ).