473,768 Members | 4,481 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

javascript to python

Could someone help me translate to something that would close to it in
python? The anonymous functions are giving me problems.

var dataListener = {
data : "",
onStartRequest: function(reques t, context){},
onStopRequest: function(reques t, context, status){
instream.close( );
outstream.close ();
listener.finish ed(this.data);
},
onDataAvailable : function(reques t, context, inputStream, offset,
count){
this.data += instream.read(c ount);
},
};
Oct 2 '08 #1
4 3121

On Oct 2, 5:54 pm, Joe Hrbek <joe.hr...@gmai l.comwrote:
Could someone help me translate to something that would close to it in
python? The anonymous functions are giving me problems.

class dataListener:
def __init__(self):
data = ""
def onStartRequest( self, request, context):
pass
def onStopRequest(s elf, request, context, status):

# TODO: pass these three in to dataListener as
# params to the constructor, so it's
# def __init__(self, instream, outstream, listener)
# and do self.instream = instream

global instream
global outstream
global listener

instream.close( )
outstream.close ()
listener.finish ed(self.data)

def onDataAvailable (self, request, context, inputStream,
offset, count):

global instream

self.data += instream.read(c ount)
question.

why are request and context being ignored?
why is there an inputStream argument to onDataAvailable , yet
there's a global variable (in the javascript) called
instream? is it the same?

all this, and more, thanks to the awfulness that is javascript :)

for fits and giggles, compile the above python using
pyjs.py, the python-to-javascript compiler
(see http://pyjamas.sf.net) and compare the
resultant javascript to your original code-fragment.

l.
Oct 2 '08 #2
On Oct 2, 7:42 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :
lkcl a écrit :
On Oct 2, 5:54 pm, Joe Hrbek <joe.hr...@gmai l.comwrote:
Could someone help me translate to something that would close to it in
python? The anonymous functions are giving me problems.
class dataListener:
def __init__(self):
data = ""
def onStartRequest( self, request, context):
pass
def onStopRequest(s elf, request, context, status):
# TODO: pass these three in to dataListener as
# params to the constructor, so it's
# def __init__(self, instream, outstream, listener)
# and do self.instream = instream
global instream
global outstream
global listener

Since you don't rebind them, you don't need the global statement for
these three identifiers
instream.close( )
outstream.close ()
listener.finish ed(self.data)
def onDataAvailable (self, request, context, inputStream,
offset, count):
global instream

idem
self.data += instream.read(c ount)

And then you have a class. Calling instance methods on the class won't
work. Looks like there's something missing...
question.
why are request and context being ignored?
why is there an inputStream argument to onDataAvailable , yet
there's a global variable (in the javascript) called
instream? is it the same?
all this, and more, thanks to the awfulness that is javascript :)

None of "this, and more" is because of javascript. You'll find bad code
in every language (and without more context, you can't tell if it's bad
code - might as well be the right thing to do).

FWIW, javascript is a very interesting and powerful language.
for fits and giggles, compile the above python using
pyjs.py, the python-to-javascript compiler
(seehttp://pyjamas.sf.net) and compare the
resultant javascript to your original code-fragment.
l.

I did. Here's the result:
ok - these are the "important" bits. notice that the pyjamas
compiler is doing a little bit more than your original code: it's
overriding the "prototype" of dataListener, making it a true "class"
object.

this is where there's a key departure from the original code and the
translation to python: the original code isn't actually a class, at
all - it's more like a.... c struct that has function pointers in it.

by declaring a python "class", the javascript equivalent is to add to
"prototypes ".

__dataListener. prototype.__ini t__ = function() {
var data = '';
};
[ ... so for example here, now when you declare _any number_ of
"dataListener"s , each and every one will have its __init__ function
called. in your original example, you're effectively making one and
only one "dataListen er". you're kinda... it's a bit like having a
lambda-class (nameless class) and declaring one and only one instance
of that python class... ]

__dataListener. prototype.onSto pRequest = function(reques t, context,
status) {
instream.close( );
outstream.close ();
listener.finish ed(this.data);
};
__dataListener. prototype.onDat aAvailable = function(reques t,
context, inputStream, offset, count) {
this.data += instream.read(c ount);
};
so - yeah, you can see that (apart from the .prototype, which is
necessary to make a "class a la javascript") it's a pretty accurate
translation back to the original javascript.

All this, and more, thanks to the strange idea that it would be better
to write javascript in Python instead of writing it in javascript !-)
*lol* :) fortunately, pyjs.py does that translation for you ha
ha. like they say on brainiac, "STOP! we do these experiments, so
you don't have to".

yes - it's because in the translated python, dataListener was
declared as a class, whereas in the original javascript, the
corresponding concept (prototypes) are not made use of.

if you wanted to experiment, you could try this:

def onStartRequest( this, request, context):
pass

def onStopRequest(t his, request, context, status):
instream.close( )
oustream.close( )
listener.finish ed(this.data)

def onDataAvailable (this, request, context,
inputStream, offset, count):
this.data += instream.read(c ount)

class dataListener:
def __init__(self):
self.data = ''
self.onStartReq uest = onStartRequest
self.onStopRequ est = onStopRequest
self.onDataAvai lable = onDataAvailable

which you will find to be more accurately representative of the
original javascript, conceptually. i.e taking into account that in
the _original_ javascript, you don't have any "prototypes ".

but - i don't believe it to be what you actually want, even though
it's "a slightly more accurate representation" .

l.
Oct 3 '08 #3
On Oct 3, 10:29 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@websiteburo.i nvalidwrote:
lkcl a écrit :On Oct 2, 7:42 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :
lkcl a écrit :
Not 'mine' - I'm not the OP.
whoops, yes - i missed that. sorry!
And as far as I'm concerned, the point is
exactly here : it's doing "a little bit more" than the original code.
yeah, i know. and that "bit more" gets you a proper representation
of the python "class" concept.

i was merely pointing out that if you want to _really_ translate the
original code into python - _really_ strictly - it's not actually
possible. because python doesn't have the concept of non-prototyping
(but... see below: i believe i may stand corrected on that)

[..snip..] and is
actually useless for the OP's use case (else the OP's code wouldn't use
litteral object notation but a full-blown prototype).
i know :)
it's
overriding the "prototype" of dataListener, making it a true "class"
object.

There's nothing like a notion of "class" in javascript - as you of
course already know.
okay,okay :) class-like :)

Indeed. But the point is that Python - while close to a prototype-based
language in many aspects - is still class-based. The closer Python
translation of the OP's javascript snippet is probably the one I gave
using a 'class singleton' - that is, using the class itself as an
object.
oh is _that_ how you do it. thanks. i always wondered how you did
class singletons in python.
python-source-to-javascript-source tool like pyjamas won't give you back
the original javascript snippet (which is by no mean a criticism of
pyjamas - it would just be way too complicated to automatize such a
translation).
well... you _say_ that... but... actually, if that's the real way to
represent class singletons, and it's an accurate representation of the
OP's javascript, and a good example, then _yes_, pyjs should
definitely have that added as a feature - to understand that a class
singleton _can_ get mapped to the much more efficient javascript
example you gave.

not that many people would _want_ to do that, so it goes onto the
"diminishin g returns TODO list", but...
Nope. You defined functions outside the object's scope, and you still
have to instanciate dataListener. Also, this above code just won't work
- unless you explicitely pass the dataListener instance to the
functions, ie:

d = dataListener()
d.onDataAvailab le(d, ...)
yeah - i didn't realise what the python class singleton thing was.
It seem you didn't read my other translation proprosal, so I repost it here:
class dataListener(ob ject):
data = ''
i did - i just didn't understand its significance.

so - to get this straight: when you do class clsname(object) , and you
have the indentation and declaration of variables (e.g. data, above)
at the same level as the functions, it means that there's only one of
them? (i.e. a singleton)?

so, if i do this:

d = dataListener()
e = dataListener()

d.data = "fred"

print f.data

will return "fred"?

l.
Oct 3 '08 #4
so, if i do this:
>
d = dataListener()
e = dataListener()

d.data = "fred"

print f.data
duh, duh - that should be print e.data :)
Oct 3 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3279
by: Michael Foord | last post by:
Please pardon my ignorance on this one - but I'm not certain how the sign bt is treated in python bitwise operators. I've trying to convert a javascript DES encryption routine into python. Javascritp has >>> and >>. >>> is a zero fill bit shift whereas >> is a sign propagating bit shift. My understanding is that the python >> is equivalent to the javascript >> - but python has no equivalent to >>>. Would a >>> 3 in javascript be...
1
1849
by: whimsica | last post by:
I'm investingating a c++ api, Panda3d.com, that has a python binding. I want to convert this api into an ACtiveX control so it will run on the web. When I do so I want to use Microsoft Script Control to call api routines from Javascript in the browser. Let's say I write up a game in python with my own functions. Then I embed it in a web page and I want to call my functions from javascript? How can I do it. Script control allows you to...
7
3737
by: Eric van Riet Paap | last post by:
Wouldn't it be nice if we could program our browser in Python instead of Javascript? - Eric
5
1902
by: Vyz | last post by:
Hi, I have a script with hundreds of lines of javascript spread accross 7 files. Is there any tool out there to automatically or semi-automatically translate the code into python. Thanks Vyz
3
2192
by: Kenneth McDonald | last post by:
I know that there's some work out there to let Python make use of Javascript (Spidermonkey) via (I assume) some sort of bridging C/C++ code. Anyone know of efforts to allow the reverse? I'd really like to make use of Python when doing Mozilla DOM programming, and I can never get a clear idea of when PyXPCOM might be available to those of us who don't know the ins and outs of compiling Mozilla, and its XPCOM structures. So if there was an...
2
10917
by: neeebs | last post by:
Hi, I'm not sure if this is a javascript problem per se, but here goes. I have an xsl document with a python function defined within a <script> block. Elsewhere in the xsl file, within a python script block, I call the python function and store the return value in a variable. I need to be able to display this returned value on the webpage that the xsl generates. I tried to do a document.write() but found that document.write() causes...
4
2462
by: Berco Beute | last post by:
I wonder what it would take to implement Python in JavaScript so it can run on those fancy new JavaScript VM's such as Chrome's V8 or Firefox' tracemonkey. Much the same as Python implementations in C# (IronPython) and Java (Jython). It would certainly bring back the fun in web application development. Is there anything done in that direction? 2B
0
1169
by: Luke Kenneth Casson Leighton | last post by:
On Sep 3, 10:02 pm, bearophileH...@lycos.com wrote: 1200 lines of code for the compiler, and about... 800 for a basic suite of builtin types (Dict, List, set, string). http://pyjamas.sf.net so it's been done.
1
2878
by: Philip Semanchuk | last post by:
On Oct 12, 2008, at 5:25 AM, S.Selvam Siva wrote: Selvam, You can try to find them yourself using string parsing, but that's difficult. The closer you want to get to "perfect" at finding URLs expressed in JS, the closer you'll get to rewriting a JS interpreter. For instance, this is not so hard to understand: "http://example.com/" but this is:
0
9407
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10171
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10015
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9842
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7384
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6656
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5280
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5425
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2808
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.