Hacker News new | past | comments | ask | show | jobs | submit login
A Python 3 implementation for client-side web programming (brython.info)
278 points by spicavigo on June 2, 2013 | hide | past | favorite | 117 comments



I can't believe all the negative comments here. Someone has implemented Python in JavaScript. I personally think that is incredible.


> Someone has implemented Python in JavaScript.

This isn't really true. This is far from a Python implementation. At best you could call it a Python-esque syntax to Javascript translator. And that's perhaps still useful. But to call this a Python implementation is quite simply a lie.


This is not a translator but an interpreter, there is no compilation.

edit: except FUD, can you provide some points on which brython is failling, please ?


Not that I have anything against Brython (which imo is a cool project, although I'm not so sure if it's practical yet), but since you asked for it, here's an example where it does differ from python:

  x = 0
  
  def impure():
      global x
      x += 1
      return x

  print(0 < impure() <= 1)
In python, impure() would only be evaluated once returning True, but Brython's chaining evaluates it twice, and so it returns False instead. Of course, this example isn't exactly something you'd usually see in actual code (heck, it's probably even bad practice in most situations) BUT the point here is that while most of python might be compatible with this, there exists some inconsistencies that causes one's previously working python code to fail (and these bugs would probably be very difficult to trace). Of course, Brython is still young and has time to hopefully fix these issues. (In fact, this is the second time I've tried this project. Back then they didn't even have the chaining feature working, so it's nice that they are making progress.)


Nifty example, but this is why we have integration test suites.

PyPy, jython, ironpython etc all had/have incompatibilities as the language evolves and as they work out the quirks in their respective runtimes.

This isn't compatible with cpython (afaik, none of the other runtimes have ever been COMPLETELY compatible, but this is much further off), but hell, it's pretty awesome.

As an aside, I'd shoot anyone who did that ^^ without a pretty amazing explaination.


Well... if brython is running the CPython integration tests to aim for proper compatibility then fair enough.

It is a cool project, whichever one of these python in javasript things is to become successful needs to aim for the same level of compatibility as say Jython or IronPython - yes it would take a long time, but this sort of thing is needed to be a useful implementation.


There's no support for metaclasses. type is missing entirely. nonlocal doesn't work. docstrings and some other double underscore names are just missing (__class__, __name__, etc.). Unicode literals don't work. dis obviously won't work since there isn't a bytecode compilation step. Scoping, like in the following code, behaves improperly:

  x = 1  
  def test():  
      print(x)  
      x = 2


I wonder if it's worth adding some failing tests to the project about these..


Things like this are why projects like pypy use CPython's test suite whereever the behavior is not CPython specific, and have contributed many tests back to CPython as well. These aren't minutia of the language, they are well understood and tested features that most moderately sized software projects are likely to rely on at some point.


That's not right, it is a translator/compiler. It simply translates a python code string into a JS code string, and then calls `eval()` on the JS code string. The `eval()` step can optionally be skipped so that you can precompile. This is much easier to implement than an interpreter anyway.


Yield support is buggy:

    def f():
        n = 0
        while n < 10:
          yield n
          n += 1
          print(n)
    g = f()
    print(next(g))
This prints 0, 1, ... 10, 0 instead of just 0


I think it's the hubris that's putting people off:

> Brython is designed to replace Javascript as the scripting language for the Web


If I wrote a Python implementation in JavaScript, I'd probably have some hubris about it as well.

I'm not sure if the developer is one person or if they wrote the landing page as well, but let's assume it is that same person.

If someone has focused enough energy to implement a language in JavaScript, it is probably fair say that marketing isn't his or her primary skill.

At the same time, reading over the text again, people have said crazier things and done much less. If the developer's goal is to replace JavaScript with Python and his or her first attempt is to implement Python in JavaScript, I, for one, applaud their effort.


That's a silly complaint. Doesn't every language designer feel that their product is better than the thing it desires to replace?


A better question: Is python really any better than JavaScript? Sure, it has advantages here and there. But there are things I like about JavaScript that are better than python. For example, having anonymous functions that are more than a single expression inside a lambda.

Yes, I know you can declare a function inside another and you get a closure. But, JavaScript's syntax is just nicer.



Wow. I had never seen that. There are literally tears streaming down my face I was laughing so hard.


I enjoyed it more this time than I did when I last saw it, perhaps because I was more familiar with the showcased peculiarities last time (the theme is garbage in, garbage out).


In all my Python years, I have never needed to write a long anonymous function. I consider it a bit of a code smell.

This isn't to say it's wrong to do in JS, just that the patterns in Python are different so you don't use this in practice.


I have never needed to write a long anonymous function.

So two line of code is long now?


Yes, as opposed to "short", i.e. a lambda. I'm sorry if my terminology offends you.


JavaScript's syntax being 'nicer' seems pretty subjective.


"It will" would register as hubris, but "designed to" seems harmless to me.


In programmers, hubris is - along with laziness and impatience - a great virtue. In Larry Wall, they gave the world Perl.


I have a better idea for a new language based on python:

    and walked: "through the valley"' he's and feared: not: "evil"!
    # he.and_walked("through the valley").and_feared(not("evil"))!

    drop down:' criminal scum!
    # criminal_scum.drop_down()!

    eat: breakfast' you!
    # you.eat(breakfast)!

    kill: with pistol' maim: blunt object' opponent's check dead:
    # opponent.maim(blunt_object).kill(with_pistol).check_dead()

    print person's name's last
    print person's last' name # ;)
    # print person.name.last

    if my's cookies's jar's empty::
        print "Cookie Monster, why is the Cookie jar empty?"
        why: cookie jar's empty:' cookie monster 

        # why cookie monster, why? :)
        why: cookie jar's empty:' cookie monster's why: "?"

it's called Glas :)


Agreed! I'm all for constructive criticism, but some of the comments in this thread are unnecessarily negative. This project looks really cool!


I really do hope this (or something like it) takes off. More choice in languages is better, and JS has been the only option for too long.

It would be amazing if browsers added interpreters natively, then we could check for a native interpreter and fall back to loading a JS one like brython.


For the curious, here's eight other fun implementations of "Python in JavaScript" to explore:

https://github.com/jashkenas/coffee-script/wiki/List-of-lang...


One not mentioned in that list is Empythoned, which is the actual CPython engine compiled to JS using Emscripten.

Repo: https://github.com/replit/empythoned

Live demo: http://repl.it/languages/Python


The way they position Brython is pretty off-putting and kind of confuses the issue.

CoffeeScript page: "CoffeeScript is a little language that compiles into JavaScript."

Brython page: "Brython is designed to replace Javascript as the scripting language for the Web."

Maybe that's the end goal, but the reality is far from it. Of course JS is still required, and of course the Python gets compiled into JS.

Finally, the approach seems a bit off. I would think it would be better for the Python to be compiled with a pre-processor, not done on the client.


The approach and the phrasing seems exactly right to me and not at all off-putting.

The goal of Brython is to replace javascript on the web, seems straightforward right? The way they go about it is to implement a compiler in javascript, and use that to bootstrap a python in the browser community. Seems like that is much easier than convincing Chrome/Firefox/IE to include a python compiler in their browser.

How would Brython replace javascript if it were precompiled on the server?


Why not provide both options, ala LESS?


Because that takes time and effort and this is relatively new.


tinco seemed to be arguing that allowing server-side compilation would be harmful to the goals of the project. That's orthogonal to your argument about time and effort.


The argument for compiling the Python with the pre-processor seems roughly analogous to traditional arguments for compiling rather than interpreting languages - i.e. how many times the conversion from source code to machine instructions must be done.

One isn't necessarily better than the other - sometimes human generated python source code in the browser may be more useful than machine generated javascript.

If nothing else, it allows us to explore a new way of constructing web apps and determine whether it is better.


I'm not sure what the commenter meant, and perhaps a silly comment to make, but doesn't python's strong indentation make it harder to simply include on a webpage? proxies, ad filters, and other optimizers might break the lines in unexpected places.

I guess it can be solved by gziping the file, or base64 encoding it. But this is also an argument (albeit trivial or weak) for compiling it on the server rather than the client.


Skulpt, PyJS and this, all good and fun experiment but all do the first 60% then they linger around. I wish they all started talking to each other and just got one single project to 90%.

Have any of these been used in production with any success. It seems like PyJS had most traction?


IMHO, This comment page is an interesting example to how unreasonably emotional programmers can be about their technology.

It looks as though, some developers are almost insulted by the idea, that someone tried to replace a language that is so commonly accepted, and that they have worked so hard to master.

This also happens in many other fields of science/technology, but I'm always surprised to see it among programmers who are considered very practical people.


If Chrome, Firefox and maybe even IE came out with support for python as a client side scripting language, the very same people here on this comment thread would happily jump on it and try to use it. The point is not about replacing one with another, but HOW it is done.


> programmers who are considered very practical people

I don't think it is universally true. Myself I know how much I can be taken away by a new technology or knowledge.


> programmers who are considered very practical people.

Ever met an Enterprise Architect?


It's too bad it didn't replace it on this page. Without JavaScript, this page is blank.


It's not the first time I had to turn on JavaScript to view a page. On the other hand, it is the first time that I have ever done so and discovered a totally logical reason for having to do so.

I got something of value by tweeking NoScript - knowledge, not just ads. Then again, I'm a yokel.


I tried it and didn't get much value out of it: What appeared was mostly just JavaScript that should have been there all along, had the page not been broken. That animated clock? Yeah, well, I can do without it.


Virtually every browser has Javascript support today. Heck, even Googlebot is executing some Javascript these days.


Noscript allows you to turn the Javascript off. Requiring javascript to see any content at all is a little absurd.


Javascript is a prerequisite of the modern web. Refusing to accept that is absurd.


First of all, he was commenting about this page not displaying ANY content at all. At the very least there should be a noscript tag to tell the user to enable JS.

Second, I whitelist sites for javascript. There's nothing absurd about that. Honestly, I can't believe people run any and all JS on every random page they land on.


> First of all, he was commenting about this page not displaying ANY content at all. At the very least there should be a noscript tag to tell the user to enable JS.

For most sites that sounds like a good idea, but this is a Javascript project. The number of people interested in a Javscript framework that don't have Javascript enabled and are still befuddled when things don't work correctly must be vanishingly small.


> For most sites that sounds like a good idea, but this is a Javascript project.

Isn't that actually the opposite argument? If you are an expert in that field, you should understand how to degrade gracefully. Besides, you might not know that the project is about javascript until you read the (blank) page.


Couldn't agree more.


>Javascript is a prerequisite of the modern web.

Citation needed.


JavaScript is like the electricity of the web. If you disable it, it's like walking around the real world with an "emp field", sure some things will still work, but it's kind of dumb to expect the modern technologies to work without their main food source.

The technologies have evolved... Why are you trying to keep us in the stone age? Or why do you expect backwards compatibility?


the http protocol is the electricity of the web , not javascript. Javascript is more like the home automation of the web and you sure can live without it. IT is stupid to offer 0 content when javascript is turned off. Some people might check the content on tablets,phones or devices that dont have javascript turned on by default.


It is part of the HTML5 spec, which is what modern browsers implement. Not supporting Javascript is not a design goal of the HTML5 project.


> Not supporting Javascript is not a design goal of the HTML5 project.

Which is why the HTML5 spec explicitly mentions disabling scripting?

"6.1.2 Enabling and disabling scripting

Scripting is enabled in a browsing context when all of the following conditions are true:

    The user agent supports scripting.
    The user has not disabled scripting for this browsing context at this time. (User agents may provide users with the option to disable scripting globally, or in a finer-grained manner, e.g. on a per-origin basis.)
    The browsing context's active document's active sandboxing flag set does not have its sandboxed scripts browsing context flag set.
"


You could also block all images and CSS; that would make for a really terrible web experience though. Why limit yourself intentionally? As a web developer I'm not going to accommodate for users that intentionally turn off features that we've been fighting for years to standardize on.


>You could also block all images and CSS; that would make for a really terrible web experience though.

The other day I was on a really spotty internet connection, lots and lots of packet loss. External CSS almost never loaded, images certainly never did. For some sites it was a pain, but for most it was bearable. Often it was an improvement, using a default font at a decent size right to the edge of my browser window. Lovely.

Of course, my browser always expected the extra crap to come down the wire, so it waited forever before actually displaying anything. If I wanted to read something in any reasonable amount of time I had to wait until the HTML was downloaded (i.e., when the title bar said something nice) then disconnect from the internet. This made my browser say, "Fuck it, let's try our best." Hitting "stop" resulted in a blank page...

I know I'm not the typical audience, but for me browsing with wget would have been a better experience.


I don't know. I think a lot of pages would be better with much less "design". You know, pages like HN where the text content is the most interesting part. Or most blogs.


Well, alrighty. I have no problem with you turning off CSS/images. But if you do, just please don't ask web developers to accommodate users like yourself. If you can disable those features, you also know how to re-enable them.


> You could also block all images and CSS; that would make for a really terrible web experience though

Really? Blocking all images can really improve your web experience in some cases.


Why is it absurd?


Noscript seems like a fetish with some people and almost always it seems they expect the rest of us to accomodate their fetish.


You can safely ignore them. They are less than 2% of Internet traffic and they know how to turn js back on.


They leave a lot more than 2% of the comments, though.


> They are less than 2% of Internet traffic

Of course. that's because their computers haven't been exploited and turned into zombies. It's hard to compete with the traffic that botnets create.


I love python and this is awesome. But I HATE magic global objects. 'ctx' seems to be at the heart of everything but is never explicitly passed into the scope or imported.

This should really be fixed.

Also "from html import *"? No no no. Never, not even once.


The ctx global and 'from html import *' are just part of the demo code. Look at line 289 of the HTML file where ctx is initialized. It's not some magic thing baked into Brython, it's just sample code. Of course you could write either of these in any way you prefer.


A demo of a new way to use a programming language shouldn't be full of these "Oh, that crap is just for the demo, it would look better in practice." It's a programming language demo, show us something that makes us want to use it.


I agree completely: sample/demo code should be the best you can make it. And I'm sure the Brython authors would welcome a pull request that improves their demo code.

But the comment I replied to was a bit misleading (no doubt unintentionally): it made two quite valid complaints about coding practices, without mentioning that these are only in the demo code.

When I read that comment I thought, "WTF? Brython injects a magic 'ctx' global into your Python code?" It doesn't, so I thought it was worth pointing out that these are just sample code issues that wouldn't affect any code you write in Brython.


"ctx" is a very common name for the "context" with which you work when doing stuff in <canvas>. There's nothing magical about it.

Also it's defined at the bottom of the script which, I admit, is a bit weird:

    if hasattr(canvas,'getContext'):
        ctx = canvas.getContext("2d")

from html import * looks bad, I agree, but I believe they did that to allow us to play with their toy from the console.


I do like the idea, but it inevitably suffers from the same flaw that afflicts all other compile-to-js libraries: making sense of errors will still require knowledge of how the underlying javascript works.

Perhaps a development plugin for Chrome would allow debugging in python?


Source maps should resolve this issue


Good point! I ashamed to say I hadn't thought much about how source maps will pave the way for anything-to-javascript web programming... very cool.


Every exception in brython has original line source, you don't need source maps. The thing is that you can't type Python in the console, yet.


Just a matter of implementing a Chrome extension to extend the developer tools with the compiler.




While I would like to see Python in the browser, this isn't it. I would still prefer coffeescript or dart over brython. Both languages aren't that hard to learn, and brython is lacking many features which would make Python more pleasant to deal with...

However, because of performance reasons, the very features that make python unique, especially the type system, are more javascript-like than python-like.

What I would like to see is a Python-implementation which is mostly feature complete, along the lines of emscripten, but still has direct access to the dom or other javascript objects.


It's a really nice demo, and I really like the idea so far (although precompiling to JS would be awesome), but I really don't see Python taking over Javascript as the scripting language.

It's way nicer in my opinion, but I think its fussy white space is likely to be an issue for this use case. All the large Javascript libraries get minified etc, and Python really isn't open to that sort of stuff. It's a great language to use normally, but I don't see it replacing Javascript. I'd much rather write in Python and compile to Javascript though.


Link to console demo from that page is broken, sadly.

edit: looks like if you remove "_en" then you get to the right place, http://www.brython.info/tests/console.html

Looks like pyjs, in that it has python syntax but JavaScript semantics, for example numbers turn into doubles here (but should be arbitrary-precision ints in Python).


Well, python 2.7:

    >>> a = 1/3
    >>> type(a)
    int
python 3.2

    >>> a = 1/3
    >>> type(a)
    <class 'float'>
brython:

    print(type(1/3))
    <class 'float'>


Correct, that's a python 2/3 difference. But both 2 and 2 have arbitrary precision integers AFAIK, try this code

    x = 1
    for i in range(100):
        x = x*2
        print(i, x)


Indeed. Just to verify that it's not just a difference in (string)representation, something like:

    print(9**32-(9**32-5))
Also works (brython returns 0, python2&3 return 5)


I love this. I wish someone would do this for Ruby.

Not CoffeeScript - I want to be able to write Ruby that manipulates DOM objects.



Last time i checked it, it contained links to old/dead projects, which seems still the case. Anyway AFAIK there is no such a similar thing to Brython for ruby, and by that I mean a ruby implementation specifically written in JS and optimized to deal with DOM and browser environment in general (if anybody knows about something like that or is working on it please inform me). It'd be such a great thing to have!


opal is very much still alive: http://opalrb.org

Most of the work in the recent weeks has been improving the ruby <=> js bridge so that calling js methods/functions from ruby is possible.


Thanks. Btw, I have nothing against Coffeescript per se. I just prefer Ruby :)


You can do it while following a similar approach to what is done for PythonScript, it's easy. PythonScript is compiled to Javascript, it use the Python abstract syntax tree module to parse python code then generate javascript. The subset of python that is (directly) translated to Javascript is PythonJS. With PythonJS is implemented some runtime stuff and higher level construct of Python. http://apppyjs.appspot.com/ Sorry the editor is broken.


I dream of a day where I can choose what language to script a page in, using a native implementation, rather than being forced to use javascript.

Javascript is great, but I'd rather work in Python and have it be actual Python, not an interpreter written in an interpreted language.


Apologies for going off-topic, but why ISN'T that an option now? Was that not the point of "type" in <script> in the first place? (That's a genuine question; I don't know the history of the <script> tag, or its "type" attribute.

How is V8 wired into Chrome, or Rhino(?) into Firefox, for example? Is there a great technical barrier to making it possible for the user to install an interpreter of their choice? As I understand the course of the browser's history, it already seems to be moving to an OS-style program (or, in Chrome's case, it has BECOME an OS), so it seems like user-loaded language runtimes OUGHT to be on SOMEONE'S mind. And I'd be surprised if it hasn't already occurred to someone before, I just don't know the history.

Has anyone attempted to write a browser that allowed for such a thing? Or has JS just been the accepted scripting language, and no one has yet tried to push past?


IIRC, Microsoft tried to get vbscript to catch on, but it didn't. I think it was a case of one language doing the trick adequately, and adding more would just multiply the headaches for development and building cross-browser compatible code. What happens when Firefox supports Python 3, Microsoft supports Python 2 (but not actual python 2, their own proprietary version) and Opera just happens to only ever run javascript?


As such, it is theoretically possible to support any scripting language on client side environment. I hope browsers will start shipping with multiple scripting engines in the future. JavaScript is not the best scripting language out there.


I don't mean to rain on anyone's parade, but how come opalrb hasn't gotten this much attention on HN (although it is a bit different from this)?

There seems to be this gah a fucking ruby developer/thing, again motif going on around HN (was hurtful at first) that makes it harder to discover cool and new ruby things!

P.S: although Python is nit my goto language, I still find this brilliant!


Opalrb has been on the HN frontpage. Why is there always someone whining about their perception of HN user sentiments lately? There's even a post whining about the user sentiments in the comments of this post on the frontpage now.


Interesting, but it is little more than a novelty.


I don't get the point why should I use Python to run Javascript.

JS has been in use around the web for a long time now and I don't see the need why should I go about using Python for the very same? Doesn't one language has a purpose of it's own?

If it wasn't the case, then people would have worked on creating a unified language for all our needs.


Nobody says you should, it's purely a personal preference :)

Doesn't one language has a purpose of it's own?

Usually no, most domains are served by more than one language, otherwise we would all be using Perl to write server-side web applications.

While it's debatable whether JavaScript is particularly well suited for client-side web code, the fact is that having only one language of choice is mostly an historical accident.


Why the hate on JavaScript? I know it's not the most elegant language in the world, but do we really need this? Instead of a program "x" run in "y", how about we just expand our horizons a bit and learn another language with different paradigms?

Python is great for some stuff, but let JS do what it does.


I don't hate javascript, and there are good arguments to learn new languages. Absolutely. But it's a bit of a my-way-or-the-highway with client-side web.

I wish I could have a choice of the language to run in the browser, and still do all the things javascript can. Having some kind of a bytecode virtual machine on the browser, that many different languages can compile to, might be the best solution.

an interesting rant from Zed Shaw on this http://vimeo.com/43380467


The issue with web (although this could be expanded to apply to most languages) is where it's used/interpreted. Browsers aren't a quickly changing environment (haha, IE 6). It takes a few years to adopt the latest and greatest. Shit, it took nearly a decade for us to see native curved corners (border-radius).

Again, not that I don't agree, it's just hard to stay up to date with the greatest while still trying to support outdated tech like html tables.

The W3C is the 'authority', but is really at the hands of the major browser manufacturers. Implementing an interpreted version of Python sounds great, but is it worth the time and effort? Will it increase my productivity or compliance compared to JavaScript? As of now, nope.

I'm happy writing bastardized JS (not that my code is bastardized, rather that's just the language [took way too long to understand == vs ===]) for the web right now. Every day new tools and frameworks are developed to make it easier, and I just don't see the advantage and overhead just to write a weird version of python that compiles into JS.


Most disappointing part of most -> js languages is that they adopt the async nature of JavaScript, thus making them pretty dissimilar from their native environments. Is it that difficult to rewrite a sync workflow to an async one by the interpreter?


You mean async to sync workflow, this is possible with generators https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_... it similar to what is done in gevent. BUT, such sync code for async is just style, the code is still async you just write it like it sync code. In this sens it can be understood as a feature of the language but generators are meant for more than that.


That's because an synchronous client-side scripting language would be useless for the web.


If you want to X to replace Y, shouldn't first order of business be letting me know why?


Very impressive work!

Issues with the examples:

I got nobody walking on the 3d walker (Chrome on Ubuntu); also it was psychedelic fun clicking into negative territory on the pie chart.


I also enjoyed the negative territory over there : )


Is it possible to minify and obfuscate python code?


Python 'compiles' to .pyc files, but I'm not show how much that compresses them, or if it's possible to reconstruct the source from it.


.pyc files are very reversible.

there are open source projects that decompile them to runnable code, the original symbol names are even intact - this means you don't lose the original naming of variables, functions, arguments, etc.


Doesn't stop you from obfuscating Python separately just like any other language, though.


They're fairly reversable out of the box. There are some modifications to cx-freeze which allow you to bundle your code in a way that makes it more difficult to reverse. What are you shipping that you need source code security with?


Being a front-end developer myself, I find such an idea a complete waste for people like me. We have put in a lot our time understanding how JS functions and most of the interactive interfaces you come across use jQuery. If Brython were to become a standard, then would you be writing a new JS library that would allow me work with DOM faster and in a better fashion?


Why not both?


What is even the need? And it needs JS to work. Not so convincing demo!


You do realize that it's a python interpreter written in Javascript?

No, browsers cannot magically run python now.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: