Re: Java to Python autoconverters

2015-06-12 Thread Michael Torrie
On 06/12/2015 05:36 AM, Sebastian M Cheung via Python-list wrote:
> Are these available? Any good ones to recommend?

The only use case for such a program that I can think of is a compiler
that is just using another language as an intermediate step, and that
language is usually going to be compiled (for example, several compilers
for different languages emit C code) or some other virtual machine like
a Javascript engine.

I don't want to put this too harshly, but the job of translating from
one language to another, and making the code idiomatic and maintainable
is up to you the programmer.  If you are a programmer you should be able
to easily do this, even if you have not worked with the source language
before.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Java to Python autoconverters

2015-06-12 Thread Ian Kelly
On Jun 12, 2015 6:53 AM, "Stefan Behnel"  wrote:
>
> Sebastian M Cheung via Python-list schrieb am 12.06.2015 um 13:36:
> > Are these available? Any good ones to recommend?
>
> I recommend not doing that. You'd end up with ugly and unidiomatic Python
> code that's impossible to maintain, whereas you now (hopefully) have
> somewhat idiomatic Java code that should be reasonably maintainable.
>
> If you want to integrate Python code with Java code, take a look at Jython
> instead. If that's not what you want, then feel free to unveil your
intentions.

I've also found Jpype useful in the past, allowing integration between
CPython and a JVM. I'm not sure if it's actively maintained, though.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Java to Python autoconverters

2015-06-12 Thread Mark Lawrence

On 12/06/2015 12:36, Sebastian M Cheung via Python-list wrote:

Are these available? Any good ones to recommend?



Yes and no.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Java to Python autoconverters

2015-06-12 Thread Stefan Behnel
Sebastian M Cheung via Python-list schrieb am 12.06.2015 um 13:36:
> Are these available? Any good ones to recommend?

I recommend not doing that. You'd end up with ugly and unidiomatic Python
code that's impossible to maintain, whereas you now (hopefully) have
somewhat idiomatic Java code that should be reasonably maintainable.

If you want to integrate Python code with Java code, take a look at Jython
instead. If that's not what you want, then feel free to unveil your intentions.

Stefan


-- 
https://mail.python.org/mailman/listinfo/python-list


Java to Python autoconverters

2015-06-12 Thread Sebastian M Cheung via Python-list
Are these available? Any good ones to recommend?
-- 
https://mail.python.org/mailman/listinfo/python-list


Pyrolite - a lightweight interface library to connect java to python

2011-07-16 Thread Irmen de Jong
Hi,

What's a java interface library doing in comp.lang.python, you might ask.

Well, this one, called 'Pyrolite' is meant to be a lightweight library (<50kb) 
to
interface your java application to Python in a very easy and straightforward 
way.

Pyrolite uses the Pyro protocol to call methods on remote objects. This means 
it also
contains an almost complete implementation of Python's pickle protocol (which 
can be
used independently).

A small piece of example code (java):

import net.razorvine.pyro.*;
NameServerProxy ns = NameServerProxy.locateNS(null);
PyroProxy something = new PyroProxy(ns.lookup("Your.Pyro.Object"));
Object result = something.call("methodname",42,"arguments",[1,2,3]);


Info, source, download and javadocs:   http://irmen.home.xs4all.nl/pyrolite/
Readonly direct svn repository access:  svn://svn.razorvine.net/Various/Pyrolite
More info on Pyro:  http://irmen.home.xs4all.nl/pyro/


Pyrolite is an experiment. You can use Jython+Pyro as well but I was interested 
in the
possibilities of a lightweight client-only library. Please let me know your 
thoughts
about it, and if you decide to use it :-)


Enjoy!

Irmen de Jong
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing array from java to python

2011-06-03 Thread Marco Nawijn
On Jun 2, 11:54 am, loial  wrote:
> I need to pass some sort of array or hashmap from Java and read the
> data in a python script (which will be called by the java class). Is
> there any neater way  to do this other than just passing strings?

I recently had to deal with the same problem, some bi-directional
communication between Java and Python. Several options were discussed
between me and my fellow programmer. In the end we settled for XML-
rpc. It works remarkably well in our case. We use it to pass test and
simulation data to GUI code. XML-rpc is very well supported in python.
Basic types (lists, dicts etc.) are encoded automatically. If the
arrays are very large, I would probably use an intermediate database
(e.g. Hdf5) for storage and then use some sort of messaging to inform
the Java code of any changes.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing array from java to python

2011-06-02 Thread Ian Kelly
On Thu, Jun 2, 2011 at 4:47 AM, loial  wrote:
> Unfortunately using jpython or json are not options at the moment

How about JPype?  Or do the Java and Python need to be in separate processes?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing array from java to python

2011-06-02 Thread Chris Rebert
On Thu, Jun 2, 2011 at 3:47 AM, loial  wrote:
> Unfortunately using jpython or json are not options at the moment

What rules out JSON that does not also rule out the "just passing
strings" approach?

What about (*shudder*) XML? (Can't believe I just said that...)

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing array from java to python

2011-06-02 Thread Nitin Pawar
can you execute the java code from python and get the result stored as
python variable os.system()



On Thu, Jun 2, 2011 at 4:17 PM, loial  wrote:

> Unfortunately using jpython or json are not options at the moment
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Nitin Pawar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing array from java to python

2011-06-02 Thread loial
Unfortunately using jpython or json are not options at the moment
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing array from java to python

2011-06-02 Thread Chris Rebert
On Thu, Jun 2, 2011 at 2:54 AM, loial  wrote:
> I need to pass some sort of array or hashmap from Java and read the
> data in a python script (which will be called by the java class). Is
> there any neater way  to do this other than just passing strings?

Jython?: http://www.jython.org/

Or depending on how you define "just passing strings", JSON:
http://json.org/
http://docs.python.org/library/json.html

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Passing array from java to python

2011-06-02 Thread loial
I need to pass some sort of array or hashmap from Java and read the
data in a python script (which will be called by the java class). Is
there any neater way  to do this other than just passing strings?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting getCSS Count Code from java to python

2011-02-17 Thread SMERSH009
On Feb 17, 10:25 pm, SMERSH009  wrote:
> On Feb 17, 9:51 pm, Stefan Behnel  wrote:
>
>
>
> > SMERSH009, 17.02.2011 22:46:
>
> > > am still stuck with the following error when I try to
> > > print self.count_css_matches('css=[id="listGuests"]')
> > > I've also included the Selenium code below. Any further help would be
> > > appreciated.
>
> > > Traceback (most recent call last):
> > >    File "D:\Temp\1TestingApps\Selenium\Scripts\SevPractice.py", line
> > > 27, in test_untitled
> > >      print self.count_css_matches('css=[id="listGuests"]')
> > >    File "D:\Temp\1TestingApps\Selenium\Scripts\SevPractice.py", line
> > > 17, in count_css_matches
> > >      return int(selenium.get_eval(self, java_script_code))
> > > TypeError: unbound method get_eval() must be called with selenium
> > > instance as first argument (got Untitled instance instead)
>
> > > --
>
> > > from selenium import selenium
> > > import unittest, time
> > > from datetime import datetime
>
> > > class Untitled(unittest.TestCase):
> > >      def count_css_matches(self, css_locator):
> > >          java_script_code = '''
> > >              var cssMatches = eval_css("%s", window.document);
> > >              cssMatches.length;''' % css_locator
> > >          return int(selenium.get_eval(self, java_script_code))
> > >          #return int(selenium.getEval(java_script_code))
>
> > You want to use "self.selenium" here, not "selenium".
>
> > Stefan
>
> > >      def setUp(self):
> > >          self.verificationErrors = []
> > >          self.selenium = selenium("localhost", 4445, "*chrome", "http://
> > >www.guestlistnation.com/")
> > >          self.selenium.start()
>
> > >      def test_untitled(self):
> > >          sel = self.selenium
> > >          sel.window_maximize()
> > >          sel.open("/Events.aspx?Location=SAN FRANCISCO")
>
> > > sel.click("css=[id='EventDates_ctl00_NestedEvents_ctl01_btnDetails']")
> > >          sel.wait_for_page_to_load("3")
>
> > >          print self.count_css_matches('css=[id="listGuests"]')
>
> > > if __name__ == "__main__":
> > >      unittest.main()
>
> Wow-- you guys rock --big time! :))
> Here is the final code with a working examples:
>
> from selenium import selenium
> import unittest, time
> from datetime import datetime
>
> class Untitled(unittest.TestCase):
>     def count_css_matches(self, css_locator):
>         java_script_code = '''
>             var cssMatches = eval_css("%s", window.document);
>             cssMatches.length;''' % css_locator
>         return self.selenium.get_eval(java_script_code)
>
>     def setUp(self):
>         self.verificationErrors = []
>         self.selenium = selenium("localhost", 4445, "*chrome", 
> "http://www.guestlistnation.com/";)
>         self.selenium.start()
>
>     def test_untitled(self):
>         sel = self.selenium
>         sel.window_maximize()
>         sel.open("/Events.aspx?Location=SAN FRANCISCO")
>
> sel.click("css=[id='EventDates_ctl00_NestedEvents_ctl01_btnDetails']")
>         sel.wait_for_page_to_load("3")
>
>         print self.count_css_matches("[id='listGuests'] > option") #
> prints number of options in dropdown with 'id=listGuests'
>         print self.count_css_matches("*") #prints all on page
> if __name__ == "__main__":
>     unittest.main()

oops, forgot to put back the int conversion!

def count_css_matches(self, css_locator):
java_script_code = '''
var cssMatches = eval_css("%s", window.document);
cssMatches.length;''' % css_locator
return int(self.selenium.get_eval(java_script_code))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting getCSS Count Code from java to python

2011-02-17 Thread Stefan Behnel

SMERSH009, 18.02.2011 07:25:

On Feb 17, 9:51 pm, Stefan Behnel wrote:

SMERSH009, 17.02.2011 22:46:

class Untitled(unittest.TestCase):
  def count_css_matches(self, css_locator):
  java_script_code = '''
  var cssMatches = eval_css("%s", window.document);
  cssMatches.length;''' % css_locator
  return int(selenium.get_eval(self, java_script_code))
  #return int(selenium.getEval(java_script_code))


You want to use "self.selenium" here, not "selenium".


Wow-- you guys rock --big time! :))


It's just Linus' Law.

http://en.wikipedia.org/wiki/Linus%27_Law

Stefan

--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting getCSS Count Code from java to python

2011-02-17 Thread SMERSH009
On Feb 17, 9:51 pm, Stefan Behnel  wrote:
> SMERSH009, 17.02.2011 22:46:
>
>
>
> > am still stuck with the following error when I try to
> > print self.count_css_matches('css=[id="listGuests"]')
> > I've also included the Selenium code below. Any further help would be
> > appreciated.
>
> > Traceback (most recent call last):
> >    File "D:\Temp\1TestingApps\Selenium\Scripts\SevPractice.py", line
> > 27, in test_untitled
> >      print self.count_css_matches('css=[id="listGuests"]')
> >    File "D:\Temp\1TestingApps\Selenium\Scripts\SevPractice.py", line
> > 17, in count_css_matches
> >      return int(selenium.get_eval(self, java_script_code))
> > TypeError: unbound method get_eval() must be called with selenium
> > instance as first argument (got Untitled instance instead)
>
> > --
>
> > from selenium import selenium
> > import unittest, time
> > from datetime import datetime
>
> > class Untitled(unittest.TestCase):
> >      def count_css_matches(self, css_locator):
> >          java_script_code = '''
> >              var cssMatches = eval_css("%s", window.document);
> >              cssMatches.length;''' % css_locator
> >          return int(selenium.get_eval(self, java_script_code))
> >          #return int(selenium.getEval(java_script_code))
>
> You want to use "self.selenium" here, not "selenium".
>
> Stefan
>
> >      def setUp(self):
> >          self.verificationErrors = []
> >          self.selenium = selenium("localhost", 4445, "*chrome", "http://
> >www.guestlistnation.com/")
> >          self.selenium.start()
>
> >      def test_untitled(self):
> >          sel = self.selenium
> >          sel.window_maximize()
> >          sel.open("/Events.aspx?Location=SAN FRANCISCO")
>
> > sel.click("css=[id='EventDates_ctl00_NestedEvents_ctl01_btnDetails']")
> >          sel.wait_for_page_to_load("3")
>
> >          print self.count_css_matches('css=[id="listGuests"]')
>
> > if __name__ == "__main__":
> >      unittest.main()
>
>

Wow-- you guys rock --big time! :))
Here is the final code with a working examples:


from selenium import selenium
import unittest, time
from datetime import datetime

class Untitled(unittest.TestCase):
def count_css_matches(self, css_locator):
java_script_code = '''
var cssMatches = eval_css("%s", window.document);
cssMatches.length;''' % css_locator
return self.selenium.get_eval(java_script_code)


def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 4445, "*chrome", "http://
www.guestlistnation.com/")
self.selenium.start()

def test_untitled(self):
sel = self.selenium
sel.window_maximize()
sel.open("/Events.aspx?Location=SAN FRANCISCO")

 
sel.click("css=[id='EventDates_ctl00_NestedEvents_ctl01_btnDetails']")
sel.wait_for_page_to_load("3")

print self.count_css_matches("[id='listGuests'] > option") #
prints number of options in dropdown with 'id=listGuests'
print self.count_css_matches("*") #prints all on page
if __name__ == "__main__":
unittest.main()




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting getCSS Count Code from java to python

2011-02-17 Thread Stefan Behnel

SMERSH009, 17.02.2011 22:46:

am still stuck with the following error when I try to
print self.count_css_matches('css=[id="listGuests"]')
I've also included the Selenium code below. Any further help would be
appreciated.

Traceback (most recent call last):
   File "D:\Temp\1TestingApps\Selenium\Scripts\SevPractice.py", line
27, in test_untitled
 print self.count_css_matches('css=[id="listGuests"]')
   File "D:\Temp\1TestingApps\Selenium\Scripts\SevPractice.py", line
17, in count_css_matches
 return int(selenium.get_eval(self, java_script_code))
TypeError: unbound method get_eval() must be called with selenium
instance as first argument (got Untitled instance instead)

--


from selenium import selenium
import unittest, time
from datetime import datetime

class Untitled(unittest.TestCase):
 def count_css_matches(self, css_locator):
 java_script_code = '''
 var cssMatches = eval_css("%s", window.document);
 cssMatches.length;''' % css_locator
 return int(selenium.get_eval(self, java_script_code))
 #return int(selenium.getEval(java_script_code))


You want to use "self.selenium" here, not "selenium".

Stefan



 def setUp(self):
 self.verificationErrors = []
 self.selenium = selenium("localhost", 4445, "*chrome", "http://
www.guestlistnation.com/")
 self.selenium.start()



 def test_untitled(self):
 sel = self.selenium
 sel.window_maximize()
 sel.open("/Events.aspx?Location=SAN FRANCISCO")

sel.click("css=[id='EventDates_ctl00_NestedEvents_ctl01_btnDetails']")
 sel.wait_for_page_to_load("3")

 print self.count_css_matches('css=[id="listGuests"]')

if __name__ == "__main__":
 unittest.main()





--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting getCSS Count Code from java to python

2011-02-17 Thread SMERSH009
On Feb 2, 7:03 am, Duncan Booth  wrote:
> Stefan Behnel  wrote:
> > You are using Selenium RC here. I have no idea if there is a Python
> > API to it or what that API looks like. The rest is just trivial code
> > that you can map 1:1 to Python:
>
> >      def count_css_matches(css_locator):
> >          java_script_code = '''
> >              var cssMatches = eval_css("%s", window.document);
> >              cssMatches.length;''' % css_locator
> >          return int(selenium.getEval(java_script_code))
>
> > Although I'd simplify the JavaScript code somewhat to make it a plain
> > expression.
>
> You also need somewhere:
>
>     from selenium import selenium
>
> and in Python the method that is needed is selenium.get_eval(...)
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com

On Feb 2, 7:03 am, Duncan Booth  wrote:
> Stefan Behnel  wrote:
> > You are using Selenium RC here. I have no idea if there is a Python
> > API to it or what that API looks like. The rest is just trivial code
> > that you can map 1:1 to Python:
>
> >  def count_css_matches(css_locator):
> >  java_script_code = '''
> >  var cssMatches = eval_css("%s", window.document);
> >  cssMatches.length;''' % css_locator
> >  return int(selenium.getEval(java_script_code))
>
> > Although I'd simplify the JavaScript code somewhat to make it a plain
> > expression.
>
> You also need somewhere:
>
> from selenium import selenium
>
> and in Python the method that is needed is selenium.get_eval(...)
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com

Hi All,
Thanks a lot for the help. I feel like I've made some progress, yet I
am still stuck with the following error when I try to
print self.count_css_matches('css=[id="listGuests"]')
I've also included the Selenium code below. Any further help would be
appreciated.

Traceback (most recent call last):
  File "D:\Temp\1TestingApps\Selenium\Scripts\SevPractice.py", line
27, in test_untitled
print self.count_css_matches('css=[id="listGuests"]')
  File "D:\Temp\1TestingApps\Selenium\Scripts\SevPractice.py", line
17, in count_css_matches
return int(selenium.get_eval(self, java_script_code))
TypeError: unbound method get_eval() must be called with selenium
instance as first argument (got Untitled instance instead)

--


from selenium import selenium
import unittest, time
from datetime import datetime

class Untitled(unittest.TestCase):
def count_css_matches(self, css_locator):
java_script_code = '''
var cssMatches = eval_css("%s", window.document);
cssMatches.length;''' % css_locator
return int(selenium.get_eval(self, java_script_code))
#return int(selenium.getEval(java_script_code))

def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 4445, "*chrome", "http://
www.guestlistnation.com/")
self.selenium.start()



def test_untitled(self):
sel = self.selenium
sel.window_maximize()
sel.open("/Events.aspx?Location=SAN FRANCISCO")
 
sel.click("css=[id='EventDates_ctl00_NestedEvents_ctl01_btnDetails']")
sel.wait_for_page_to_load("3")

print self.count_css_matches('css=[id="listGuests"]')

if __name__ == "__main__":
unittest.main()


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting getCSS Count Code from java to python

2011-02-02 Thread Duncan Booth
Stefan Behnel  wrote:

> You are using Selenium RC here. I have no idea if there is a Python
> API to it or what that API looks like. The rest is just trivial code
> that you can map 1:1 to Python:
> 
>  def count_css_matches(css_locator):
>  java_script_code = '''
>  var cssMatches = eval_css("%s", window.document);
>  cssMatches.length;''' % css_locator
>  return int(selenium.getEval(java_script_code))
> 
> Although I'd simplify the JavaScript code somewhat to make it a plain 
> expression.

You also need somewhere:

from selenium import selenium

and in Python the method that is needed is selenium.get_eval(...)

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting getCSS Count Code from java to python

2011-02-02 Thread Stefan Behnel

SMERSH009, 01.02.2011 05:23:

Hi, I'd love some help converting this code to the python equivalent:

private int getCSSCount(String aCSSLocator){
 String jsScript = "var cssMatches = eval_css(\"%s\",
window.document);cssMatches.length;";
 return Integer.parseInt(selenium.getEval(String.format(jsScript,
aCSSLocator)));
}

http://www.eviltester.com/index.php/2010/03/13/a-simple-getcsscount-helper-method-for-use-with-selenium-rc/


You are using Selenium RC here. I have no idea if there is a Python API to 
it or what that API looks like. The rest is just trivial code that you can 
map 1:1 to Python:


def count_css_matches(css_locator):
java_script_code = '''
var cssMatches = eval_css("%s", window.document);
cssMatches.length;''' % css_locator
return int(selenium.getEval(java_script_code))

Although I'd simplify the JavaScript code somewhat to make it a plain 
expression.


If that's not what you want, please be more precise, or look at the CSS 
selectors in lxml that Jon Clemens pointed you to.


Stefan

--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting getCSS Count Code from java to python

2011-02-02 Thread Jon Clements
On Feb 1, 4:23 am, SMERSH009  wrote:
> Hi, I'd love some help converting this code to the python equivalent:
>
> private int getCSSCount(String aCSSLocator){
>     String jsScript = "var cssMatches = eval_css(\"%s\",
> window.document);cssMatches.length;";
>     return Integer.parseInt(selenium.getEval(String.format(jsScript,
> aCSSLocator)));
>
> }
>
> http://www.eviltester.com/index.php/2010/03/13/a-simple-getcsscount-h...
>
> Thanks for the help

Maybe?

http://codespeak.net/lxml/dev/cssselect.html

Jon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Converting getCSS Count Code from java to python

2011-01-31 Thread SMERSH009
Hi, I'd love some help converting this code to the python equivalent:

private int getCSSCount(String aCSSLocator){
String jsScript = "var cssMatches = eval_css(\"%s\",
window.document);cssMatches.length;";
return Integer.parseInt(selenium.getEval(String.format(jsScript,
aCSSLocator)));
}

http://www.eviltester.com/index.php/2010/03/13/a-simple-getcsscount-helper-method-for-use-with-selenium-rc/

Thanks for the help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Java-to-Python?

2009-12-18 Thread Luis M . González
On Dec 18, 11:44 am, Virgil Stokes  wrote:
> I have a rather large Java package for the analysis of networks that I
> would like to convert to Python. Many of the classes in the Java package
> are "Serializable".
>
> Any recommendations on Java-to-Python (2.6) would be appreciated.
>
> --V

Have you considered using this package with Jython?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Java-to-Python?

2009-12-18 Thread Tim Wintle
On Fri, 2009-12-18 at 15:44 +0100, Virgil Stokes wrote:
> I have a rather large Java package for the analysis of networks that I 
> would like to convert to Python. Many of the classes in the Java package 
> are "Serializable".
> 
> Any recommendations on Java-to-Python (2.6) would be appreciated.

I used java2python recently with quite a lot of success. I believe it
doesn't support newer java features though.

http://code.google.com/p/java2python/

-- 
http://mail.python.org/mailman/listinfo/python-list


Java-to-Python?

2009-12-18 Thread Virgil Stokes
I have a rather large Java package for the analysis of networks that I 
would like to convert to Python. Many of the classes in the Java package 
are "Serializable".


Any recommendations on Java-to-Python (2.6) would be appreciated.

--V



--
http://mail.python.org/mailman/listinfo/python-list


The TimingAnalyzer -- project to convert from Java to Python

2009-07-03 Thread chewie
Hello,

This a project related to the development of an EDA CAD tool program
called the TimingAnalyzer.  Digital engineers could use this kind of
program to analyze and document inteface timing diagrams  for IC,
ASIC, FPGA, and board level hardware projects.

The TimingAnalyzer is licensed as freeware.   I don't have the time
needed to make a high quality commercial product but I do want to keep
the development moving forward and continue to fix problems and add
new features as time permits.

www.timing-diagrams.com

Recently, I have become very interested in Python and using it to
develop similar type cad programs.  My plan is to convert the
TimingAnalyzer Java to Python with mostly a scripting interface for
building complex timing diagrams, doing timing analysis,  creating
testbenches and testvectors from waveform diagrams,
and creating timing diagrams from simulation VCD files.  Most all of
this is text based work anyway.

Developing professional GUIs is very time consuming for me.  This has
been my bottleneck with the program all along.  With a command line
interface,  you will execute a script and in one window,  and view and
edit and print the timing diagram shown in another window.   Like the
Matlab interface.

For example:

micro = m68000()
micro.write(add, data, wait_states)
micro.read(add, wait_states).

or

add_clock(..)
add_signal(.)
add_delay(..)
add_constraint(.)
add_or_gate()
add_and_gate()
add_counter()
add_clock_jitter(.)

analyze_clock_domains(.)
analyze_worst_case_timings()
analyze_best_case_timings.

read_vcd()
vcd_2_timing_diagram(.)
create_testvectors(.)
create_testbench()

A lot of these functions are built into the program now so its a
matter of converting them java to python.  I won't have to spend most
of the time getting the user interface to look good and be friendly.
If this is made an open source project,  I would hope that others
would help with the development and new features and bug fixes will so
progress will be made quickly.

If anyone is interested in helping with the development,  I will make
this an open source project.   Just let me know if your interested.

Thank you,
Dan Fabrizio
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Java to Python

2009-02-07 Thread Aleksandar Radulovic
Hi,

On Sat, Feb 7, 2009 at 5:28 PM, zaheer agadi  wrote:
> Thanks Alex,
>
>  Can you provide me more details on httplib and urllib ?

The details can be found in Python documentation (http://python.org/doc),
on these pages:
http://docs.python.org/library/httplib.html

I'm sure you can figure out the location of the documentation for the urllib2
module. Documentation includes examples too.


Regards,
alex.
-- 
a lex 13 x
http://www.a13x.info
--
http://mail.python.org/mailman/listinfo/python-list


Re: Java to Python

2009-02-07 Thread Aleksandar Radulovic
Hi,

This looks like a perfect job for httplib and urllib2 modules.

On Sat, Feb 7, 2009 at 4:49 PM, zaheer agadi  wrote:
> Hi Thanks for replying ..
> I am actually looking for the pure Python options
>
> Are there any equivalent clasees  for the following
>
> import org.apache.commons.httpclient.HttpClient;
> import org.apache.commons.httpclient.HttpException;
> import
> org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
> import org.apache.commons.httpclient.methods.GetMethod;
> import org.apache.commons.httpclient.protocol.Protocol;
>
>
> Thanks for your help
> -Zaheer
>
> On Sat, Feb 7, 2009 at 9:57 PM, Banibrata Dutta 
> wrote:
>>
>> Jython is not an option ?
>>
>> On Sat, Feb 7, 2009 at 9:54 PM,  wrote:
>>>
>>> Hi
>>>
>>> I have a following class that is written Java and makes use of apache
>>> http client library,I am new to python can any one suggest me a python
>>> equivalent of this following class,
>>>
>>> Thanks ,
>>>
>>> public class Authenticate{
>>>
>>>  private String storageUserName=null;
>>>private String storagePassword=null;
>>>private String authorization=null;
>>>private String identityHostName = null;
>>>private String identityPortNumber = null;
>>>
>>>private String accessKey=null;
>>>private String secretKey=null;
>>>
>>>public String getStoragePassword() {
>>>return storagePassword;
>>>}
>>>
>>>public void setStoragePassword(String storagePassword) {
>>>this.storagePassword = storagePassword;
>>>}
>>>
>>>public String getStorageUserName() {
>>>return storageUserName;
>>>}
>>>
>>>public void setStorageUserName(String storageUserName) {
>>>this.storageUserName = storageUserName;
>>>}
>>>
>>>public String getIdentityHostName() {
>>>return identityHostName;
>>>}
>>>
>>>public void setIdentityHostName(String identityHostName) {
>>>this.identityHostName = identityHostName;
>>>}
>>>
>>>public String getIdentityPortNumber() {
>>>return identityPortNumber;
>>>}
>>>
>>>public void setIdentityPortNumber(String identityPortNumber) {
>>>this.identityPortNumber = identityPortNumber;
>>>}
>>>
>>>public String getAccessKey() {
>>>return accessKey;
>>>}
>>>
>>>public void setAccessKey(String accessKey) {
>>>this.accessKey = accessKey;
>>>}
>>>
>>>public String getSecretKey() {
>>>return secretKey;
>>>}
>>>
>>>public void setSecretKey(String secretKey) {
>>>this.secretKey = secretKey;
>>>}
>>>
>>>
>>> /**
>>> * Convenience string for Base 64 encoding.
>>> */
>>>private static final String BASE64_CHARS =
>>>"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
>>>"abcdefghijklmnopqrstuvwxyz" +
>>>"0123456789+/";
>>>
>>>/**
>>> * Encode the specified credentials into a String as required
>>> by
>>> * HTTP Basic Authentication (http://www.ietf.org/rfc/
>>> rfc2617.txt">RFC 2617).
>>> *
>>> * @param username Username to be encoded
>>> * @param password Password to be encoded
>>> * @return String string containing encoded username and password.
>>> */
>>>public String encodeCredentialsBasic(String username, String
>>> password) {
>>>String encode = username + ":" + password;
>>>int paddingCount = (3 - (encode.length() % 3)) % 3;
>>>encode += "\0\0".substring(0, paddingCount);
>>>StringBuilder encoded = new StringBuilder();
>>>
>>>for (int i = 0; i < encode.length(); i += 3) {
>>>}
>>>return encoded.toString();
>>>}
>>>
>>>public void fetchDetails(){
>>>HttpClient client=new HttpClient();
>>>//reqDetails = new RequestDetails();
>>>//String identityURL=MessageUtil.getMessage
>>> ("IDENTITY_INSTANCE");
>>>//int portNumber=Integer.parseInt(MessageUtil.getMessage
>>> ("IDENTITY_PORT"));
>>>authorization="Basic " + encodeCredentialsBasic
>>> (storageUserName, storagePassword);
>>>String url="https://"+identityHostName+
>>>":"+identityPortNumber+"/test/ndcsd2/persons/"+UserName
>>> +"/attributes/";
>>>
>>>Protocol https=null;
>>>//try {
>>>https = new Protocol("https", new
>>> EasySSLProtocolSocketFactory(), Integer.parseInt(identityPortNumber));
>>>/*} catch (GeneralSecurityException ex) {
>>>Logger.getLogger(Authenticate.class.getName()).log
>>> (Level.SEVERE, null, ex);
>>>} catch (IOException ex) {
>>>Logger.getLogger(Authenticate.class.getName()).log
>>> (Level.SEVERE, null, ex);
>>>}*/
>>>Protocol.registerProtocol("https", https);
>>>GetMethod method=new GetMethod(url);
>>>method.setRequestHeader("Authorization",authorization);
>>>method.setRequestHeader("Accept","application/xml");
>>>try {
>>>int responseCode=client.executeMethod(method);
>>>

Re: Java to Python

2009-02-07 Thread zaheer agadi
Hi Thanks for replying ..
I am actually looking for the pure Python options

Are there any equivalent clasees  for the following

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import
org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.protocol.Protocol;


Thanks for your help
-Zaheer

On Sat, Feb 7, 2009 at 9:57 PM, Banibrata Dutta
wrote:

> Jython is not an option ?
>
> On Sat, Feb 7, 2009 at 9:54 PM,  wrote:
>
>> Hi
>>
>> I have a following class that is written Java and makes use of apache
>> http client library,I am new to python can any one suggest me a python
>> equivalent of this following class,
>>
>> Thanks ,
>>
>> public class Authenticate{
>>
>>  private String storageUserName=null;
>>private String storagePassword=null;
>>private String authorization=null;
>>private String identityHostName = null;
>>private String identityPortNumber = null;
>>
>>private String accessKey=null;
>>private String secretKey=null;
>>
>>public String getStoragePassword() {
>>return storagePassword;
>>}
>>
>>public void setStoragePassword(String storagePassword) {
>>this.storagePassword = storagePassword;
>>}
>>
>>public String getStorageUserName() {
>>return storageUserName;
>>}
>>
>>public void setStorageUserName(String storageUserName) {
>>this.storageUserName = storageUserName;
>>}
>>
>>public String getIdentityHostName() {
>>return identityHostName;
>>}
>>
>>public void setIdentityHostName(String identityHostName) {
>>this.identityHostName = identityHostName;
>>}
>>
>>public String getIdentityPortNumber() {
>>return identityPortNumber;
>>}
>>
>>public void setIdentityPortNumber(String identityPortNumber) {
>>this.identityPortNumber = identityPortNumber;
>>}
>>
>>public String getAccessKey() {
>>return accessKey;
>>}
>>
>>public void setAccessKey(String accessKey) {
>>this.accessKey = accessKey;
>>}
>>
>>public String getSecretKey() {
>>return secretKey;
>>}
>>
>>public void setSecretKey(String secretKey) {
>>this.secretKey = secretKey;
>>}
>>
>>
>> /**
>> * Convenience string for Base 64 encoding.
>> */
>>private static final String BASE64_CHARS =
>>"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
>>"abcdefghijklmnopqrstuvwxyz" +
>>"0123456789+/";
>>
>>/**
>> * Encode the specified credentials into a String as required
>> by
>> * HTTP Basic Authentication (http://www.ietf.org/rfc/
>> rfc2617.txt ">RFC 2617).
>> *
>> * @param username Username to be encoded
>> * @param password Password to be encoded
>> * @return String string containing encoded username and password.
>> */
>>public String encodeCredentialsBasic(String username, String
>> password) {
>>String encode = username + ":" + password;
>>int paddingCount = (3 - (encode.length() % 3)) % 3;
>>encode += "\0\0".substring(0, paddingCount);
>>StringBuilder encoded = new StringBuilder();
>>
>>for (int i = 0; i < encode.length(); i += 3) {
>>}
>>return encoded.toString();
>>}
>>
>>public void fetchDetails(){
>>HttpClient client=new HttpClient();
>>//reqDetails = new RequestDetails();
>>//String identityURL=MessageUtil.getMessage
>> ("IDENTITY_INSTANCE");
>>//int portNumber=Integer.parseInt(MessageUtil.getMessage
>> ("IDENTITY_PORT"));
>>authorization="Basic " + encodeCredentialsBasic
>> (storageUserName, storagePassword);
>>String url="https://"+identityHostName+
>>":"+identityPortNumber+"/test/ndcsd2/persons/"+UserName
>> +"/attributes/";
>>
>>Protocol https=null;
>>//try {
>>https = new Protocol("https", new
>> EasySSLProtocolSocketFactory(), Integer.parseInt(identityPortNumber));
>>/*} catch (GeneralSecurityException ex) {
>>Logger.getLogger(Authenticate.class.getName()).log
>> (Level.SEVERE, null, ex);
>>} catch (IOException ex) {
>>Logger.getLogger(Authenticate.class.getName()).log
>> (Level.SEVERE, null, ex);
>>}*/
>>Protocol.registerProtocol("https", https);
>>GetMethod method=new GetMethod(url);
>>method.setRequestHeader("Authorization",authorization);
>>method.setRequestHeader("Accept","application/xml");
>>try {
>>int responseCode=client.executeMethod(method);
>>if(responseCode==200){
>>InputStream is=method.getResponseBodyAsStream();
>>BufferedReader bis=new BufferedReader(new
>> InputStreamReader(is));
>>String temp=null,sKey=null, aKey=null;
>> 

Re: Java to Python

2009-02-07 Thread Banibrata Dutta
Jython is not an option ?

On Sat, Feb 7, 2009 at 9:54 PM,  wrote:

> Hi
>
> I have a following class that is written Java and makes use of apache
> http client library,I am new to python can any one suggest me a python
> equivalent of this following class,
>
> Thanks ,
>
> public class Authenticate{
>
>  private String storageUserName=null;
>private String storagePassword=null;
>private String authorization=null;
>private String identityHostName = null;
>private String identityPortNumber = null;
>
>private String accessKey=null;
>private String secretKey=null;
>
>public String getStoragePassword() {
>return storagePassword;
>}
>
>public void setStoragePassword(String storagePassword) {
>this.storagePassword = storagePassword;
>}
>
>public String getStorageUserName() {
>return storageUserName;
>}
>
>public void setStorageUserName(String storageUserName) {
>this.storageUserName = storageUserName;
>}
>
>public String getIdentityHostName() {
>return identityHostName;
>}
>
>public void setIdentityHostName(String identityHostName) {
>this.identityHostName = identityHostName;
>}
>
>public String getIdentityPortNumber() {
>return identityPortNumber;
>}
>
>public void setIdentityPortNumber(String identityPortNumber) {
>this.identityPortNumber = identityPortNumber;
>}
>
>public String getAccessKey() {
>return accessKey;
>}
>
>public void setAccessKey(String accessKey) {
>this.accessKey = accessKey;
>}
>
>public String getSecretKey() {
>return secretKey;
>}
>
>public void setSecretKey(String secretKey) {
>this.secretKey = secretKey;
>}
>
>
> /**
> * Convenience string for Base 64 encoding.
> */
>private static final String BASE64_CHARS =
>"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
>"abcdefghijklmnopqrstuvwxyz" +
>"0123456789+/";
>
>/**
> * Encode the specified credentials into a String as required
> by
> * HTTP Basic Authentication (http://www.ietf.org/rfc/
> rfc2617.txt">RFC 2617).
> *
> * @param username Username to be encoded
> * @param password Password to be encoded
> * @return String string containing encoded username and password.
> */
>public String encodeCredentialsBasic(String username, String
> password) {
>String encode = username + ":" + password;
>int paddingCount = (3 - (encode.length() % 3)) % 3;
>encode += "\0\0".substring(0, paddingCount);
>StringBuilder encoded = new StringBuilder();
>
>for (int i = 0; i < encode.length(); i += 3) {
>}
>return encoded.toString();
>}
>
>public void fetchDetails(){
>HttpClient client=new HttpClient();
>//reqDetails = new RequestDetails();
>//String identityURL=MessageUtil.getMessage
> ("IDENTITY_INSTANCE");
>//int portNumber=Integer.parseInt(MessageUtil.getMessage
> ("IDENTITY_PORT"));
>authorization="Basic " + encodeCredentialsBasic
> (storageUserName, storagePassword);
>String url="https://"+identityHostName+
>":"+identityPortNumber+"/test/ndcsd2/persons/"+UserName
> +"/attributes/";
>
>Protocol https=null;
>//try {
>https = new Protocol("https", new
> EasySSLProtocolSocketFactory(), Integer.parseInt(identityPortNumber));
>/*} catch (GeneralSecurityException ex) {
>Logger.getLogger(Authenticate.class.getName()).log
> (Level.SEVERE, null, ex);
>} catch (IOException ex) {
>Logger.getLogger(Authenticate.class.getName()).log
> (Level.SEVERE, null, ex);
>}*/
>Protocol.registerProtocol("https", https);
>GetMethod method=new GetMethod(url);
>method.setRequestHeader("Authorization",authorization);
>method.setRequestHeader("Accept","application/xml");
>try {
>int responseCode=client.executeMethod(method);
>if(responseCode==200){
>InputStream is=method.getResponseBodyAsStream();
>BufferedReader bis=new BufferedReader(new
> InputStreamReader(is));
>String temp=null,sKey=null, aKey=null;
>String accessKeySearchString="AccessKey Name>";
>String secretKeySearchString="SecretKey Name>";
>int searchStringLength=0;
>while((temp=bis.readLine())!=null){
>if(temp.indexOf(accessKeySearchString)!=-1){
>int beginIndex=temp.indexOf
> (accessKeySearchString);
>searchStringLength=accessKeySearchString.length
> ();
>int endIndex=temp.indexOf(" Value>",beginIndex);
>aKey=temp.substring(beginIndex
> +searchStringLength,endIndex);
>}
>if(temp.indexOf(secretKeySearchString)!=-1){
> 

Java to Python

2009-02-07 Thread zaheer . agadi
Hi

I have a following class that is written Java and makes use of apache
http client library,I am new to python can any one suggest me a python
equivalent of this following class,

Thanks ,

public class Authenticate{

 private String storageUserName=null;
private String storagePassword=null;
private String authorization=null;
private String identityHostName = null;
private String identityPortNumber = null;

private String accessKey=null;
private String secretKey=null;

public String getStoragePassword() {
return storagePassword;
}

public void setStoragePassword(String storagePassword) {
this.storagePassword = storagePassword;
}

public String getStorageUserName() {
return storageUserName;
}

public void setStorageUserName(String storageUserName) {
this.storageUserName = storageUserName;
}

public String getIdentityHostName() {
return identityHostName;
}

public void setIdentityHostName(String identityHostName) {
this.identityHostName = identityHostName;
}

public String getIdentityPortNumber() {
return identityPortNumber;
}

public void setIdentityPortNumber(String identityPortNumber) {
this.identityPortNumber = identityPortNumber;
}

public String getAccessKey() {
return accessKey;
}

public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}

public String getSecretKey() {
return secretKey;
}

public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}


 /**
 * Convenience string for Base 64 encoding.
 */
private static final String BASE64_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789+/";

/**
 * Encode the specified credentials into a String as required
by
 * HTTP Basic Authentication (http://www.ietf.org/rfc/
rfc2617.txt">RFC 2617).
 *
 * @param username Username to be encoded
 * @param password Password to be encoded
 * @return String string containing encoded username and password.
 */
public String encodeCredentialsBasic(String username, String
password) {
String encode = username + ":" + password;
int paddingCount = (3 - (encode.length() % 3)) % 3;
encode += "\0\0".substring(0, paddingCount);
StringBuilder encoded = new StringBuilder();

for (int i = 0; i < encode.length(); i += 3) {
}
return encoded.toString();
}

public void fetchDetails(){
HttpClient client=new HttpClient();
//reqDetails = new RequestDetails();
//String identityURL=MessageUtil.getMessage
("IDENTITY_INSTANCE");
//int portNumber=Integer.parseInt(MessageUtil.getMessage
("IDENTITY_PORT"));
authorization="Basic " + encodeCredentialsBasic
(storageUserName, storagePassword);
String url="https://"+identityHostName+
":"+identityPortNumber+"/test/ndcsd2/persons/"+UserName
+"/attributes/";

Protocol https=null;
//try {
https = new Protocol("https", new
EasySSLProtocolSocketFactory(), Integer.parseInt(identityPortNumber));
/*} catch (GeneralSecurityException ex) {
Logger.getLogger(Authenticate.class.getName()).log
(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Authenticate.class.getName()).log
(Level.SEVERE, null, ex);
}*/
Protocol.registerProtocol("https", https);
GetMethod method=new GetMethod(url);
method.setRequestHeader("Authorization",authorization);
method.setRequestHeader("Accept","application/xml");
try {
int responseCode=client.executeMethod(method);
if(responseCode==200){
InputStream is=method.getResponseBodyAsStream();
BufferedReader bis=new BufferedReader(new
InputStreamReader(is));
String temp=null,sKey=null, aKey=null;
String accessKeySearchString="AccessKey";
String secretKeySearchString="SecretKey";
int searchStringLength=0;
while((temp=bis.readLine())!=null){
if(temp.indexOf(accessKeySearchString)!=-1){
int beginIndex=temp.indexOf
(accessKeySearchString);
searchStringLength=accessKeySearchString.length
();
int endIndex=temp.indexOf("",beginIndex);
aKey=temp.substring(beginIndex
+searchStringLength,endIndex);
}
if(temp.indexOf(secretKeySearchString)!=-1){
int beginIndex=temp.indexOf
(secretKeySearchString);
searchStringLength=secretKeySearchString.length
();
int endIndex=temp.indexOf("",beginIndex);
sKey=temp.subs

Re: Moving from java to python.

2007-11-12 Thread Larry Bates
Paul Hankin wrote:
> On Nov 12, 3:25 pm, "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I have recently been learning python, and coming from a java
>> background there are many new ways of doing things that I am only just
>> getting to grips with.
>>
>> I wondered if anyone could take a look at a few pieces of code I have
>> written to see if there are any places where I am still using java-
>> esque techniques, and letting me know the appropriate python way of
>> doing things.
>>
>> Here is a node class I wrote for use in graph traversal algorithms:
>>
>> #
>>
>> class Node:
>> """
>> Node models a single piece of connected data.
>>
>> Author: Peter Braden
>> Last Modified : Nov. '07
>> """
>>
>> def __init__(self, connections = None, uid = None):
>> """
>> Args:
>> [connections - a list of (connected node, weight) 
>> tuples.   ]
>> [uid - an identifier for comparisons.]
>> """
>> self._connected = []
>> self._weights = []
>>
>> if connections:
>> for i in connections:
>> self.connected.append(i[0])
>> self.weights.append(i[1])
>>
>> if not uid:
>> self.id = id(self)
>> else:
>> self.id = uid
>>
>> def __eq__(self, other):
>> return self.id == other.id
>>
>> def getConnected(self):
>> return self._connected
>>
>> def getWeights(self):
>> return self._weights
>>
>> def getConnections(self):
>> connections = []
>> for i in range(len(connected)):
>> 
>> connections.append((self._connected[i],self._weight[i]))
>> return connections
>>
>> connected = property(getConnected, None)
>> weights = property (getWeights, None)
>> connections = property(getConnections, None)
>>
>> def addConnection(self, node, weight = 0):
>> self.connected.append(node)
>> self.weights.append(weight)
>>
>> def removeConnection(self, node):
>> i = self._connected.index(node)
>> del self._connected[i]
>> del self._weights[i]
> 
> There's no reason to make 'connected' and 'weights' properties: just
> use them directly.
> 
> Make 'connections' default to [] rather than None, and replace the
> slightly clumsy initialisation with more direct code:
> 
> self.connected = [i[0] for i in connections]
> self.weights = [i[1] for i in connections]
> 
> getConnections can be much simpler...
> 
> def getConnections(self):
> return zip(self.connected, self.weights)
> 
> The 'uid' business makes me suspicious: what's it for? If you need it,
> you probably need to initialise with an explicit test for None rather
> than just 'if uid' which will be wrong if you use a uid of 0...
> 
> self.id = uid if uid is not None else id(self)
> 
> HTH
> --
> Paul Hankin
> 
Be VERY careful with using [] as default arguments.  Mutables are only 
evaluated 
once (not at every call).  This question comes up about once a week on this 
forum where people don't understand this.

I would recommend using (if you can):

def __init__(self, connected = None, weights=None, uid = None):
self.connected = connected or []
self.weights = weights or []


If you want to stay with single connections list do this:

def __init__(self, connections = None, uid = None):
 if connections is not None:
 self.connected=[c[0] for c in connections]
 self.weights=[c(1) for c in connections]

else:
 self.connected=[]
 self.weights=[]

Others have addressed the lack of need for accessors.

-Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving from java to python.

2007-11-12 Thread Tim Chase
 >   def __init__(self, connections = None, uid = None):
 > """
 > Args:
 >   [connections - a list of (connected node, weight) tuples.  ]
 >   [uid - an identifier for comparisons.]
 > """
 > self._connected = []
 > self._weights = []
 >
 > if connections:
 >   for i in connections:
 > self.connected.append(i[0])
 > self.weights.append(i[1])

I'd likely write this something like

   if connections:
 self.connected, self.weights = zip(*connections)

You also shift here between "_connected" and "connected" (same 
with weights).  This might bite you.

 > if not uid:
 >   self.id = id(self)
 > else:
 >   self.id = uid

A common way of writing this would be

   self.id = uid or id(self)

However, the need for anything other than the id() is suspect. 
Imaginable, but suspect.

 >   def getConnected(self):
 > return self._connected
 >
 >   def getWeights(self):
 > return self._weights
 >   connected = property(getConnected, None)
 >   weights = property (getWeights, None)

No need for properties at this time...they can be added 
transparently later, if you need to do something programatic on 
access.

 >   def getConnections(self):
 > connections = []
 > for i in range(len(connected)):
 >   connections.append((self._connected[i],self._weight[i]))
 > return connections
 >
 >   connections = property(getConnections, None)

And in an inverse of the __init__ method, I'd use something like

   def getConnections(self):
 return zip(self.connected, self.weights)

Just my first-pass thoughts...

-tkc




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving from java to python.

2007-11-12 Thread Hrvoje Niksic
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

>   def __init__(self, connections = None, uid = None):

You can use connections=(), so you don't need the "if" below.  In
fact, you can further write:

for node, weight in connections:
self._connected.append(node)
self._weight.append(weight)

>   def getConnected(self):
>   return self._connected

I'd drop the getters and simply use self.connected, self.weights, etc.
It's not such a big deal in Python if someone can view the innards of
your objects; they can do so even if their name starts with _.

Also note that Python doesn't really use the camel-case naming
convention.  If you must have multi-word method/variable/property
names, use lower-case with underscores for separation.  For example:

>   def getConnections(self):

Why not simply def connections(self) or, if you must, def
get_connections(self).

>   connections = []
>   for i in range(len(connected)):
>   connections.append((self._connected[i],self._weight[i]))

Use xrange(len(...)) when iterating over the sequence; range
unnecessarily allocates the whole list.  Some will probably recommend
enumerate() or even itertools.izip(), but those are overkill for this
usage.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving from java to python.

2007-11-12 Thread Paul Hankin
On Nov 12, 3:25 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have recently been learning python, and coming from a java
> background there are many new ways of doing things that I am only just
> getting to grips with.
>
> I wondered if anyone could take a look at a few pieces of code I have
> written to see if there are any places where I am still using java-
> esque techniques, and letting me know the appropriate python way of
> doing things.
>
> Here is a node class I wrote for use in graph traversal algorithms:
>
> #
>
> class Node:
> """
> Node models a single piece of connected data.
>
> Author: Peter Braden
> Last Modified : Nov. '07
> """
>
> def __init__(self, connections = None, uid = None):
> """
> Args:
> [connections - a list of (connected node, weight) 
> tuples.   ]
> [uid - an identifier for comparisons.]
> """
> self._connected = []
> self._weights = []
>
> if connections:
> for i in connections:
> self.connected.append(i[0])
> self.weights.append(i[1])
>
> if not uid:
> self.id = id(self)
> else:
> self.id = uid
>
> def __eq__(self, other):
> return self.id == other.id
>
> def getConnected(self):
> return self._connected
>
> def getWeights(self):
> return self._weights
>
> def getConnections(self):
> connections = []
> for i in range(len(connected)):
> 
> connections.append((self._connected[i],self._weight[i]))
> return connections
>
> connected = property(getConnected, None)
> weights = property (getWeights, None)
> connections = property(getConnections, None)
>
> def addConnection(self, node, weight = 0):
> self.connected.append(node)
> self.weights.append(weight)
>
> def removeConnection(self, node):
> i = self._connected.index(node)
> del self._connected[i]
> del self._weights[i]

There's no reason to make 'connected' and 'weights' properties: just
use them directly.

Make 'connections' default to [] rather than None, and replace the
slightly clumsy initialisation with more direct code:

self.connected = [i[0] for i in connections]
self.weights = [i[1] for i in connections]

getConnections can be much simpler...

def getConnections(self):
return zip(self.connected, self.weights)

The 'uid' business makes me suspicious: what's it for? If you need it,
you probably need to initialise with an explicit test for None rather
than just 'if uid' which will be wrong if you use a uid of 0...

self.id = uid if uid is not None else id(self)

HTH
--
Paul Hankin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving from java to python.

2007-11-12 Thread Jarek Zgoda
[EMAIL PROTECTED] napisał(a):

>   def getConnected(self):
>   return self._connected

No need to use accessors. Just plain attribute lookup is sufficient.

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101

"We read Knuth so you don't have to." (Tim Peters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Moving from java to python.

2007-11-12 Thread [EMAIL PROTECTED]
Hi,

I have recently been learning python, and coming from a java
background there are many new ways of doing things that I am only just
getting to grips with.

I wondered if anyone could take a look at a few pieces of code I have
written to see if there are any places where I am still using java-
esque techniques, and letting me know the appropriate python way of
doing things.


Here is a node class I wrote for use in graph traversal algorithms:

#

class Node:
"""
Node models a single piece of connected data.

Author: Peter Braden
Last Modified : Nov. '07
"""

def __init__(self, connections = None, uid = None):
"""
Args:
[connections - a list of (connected node, weight) 
tuples.   ]
[uid - an identifier for comparisons.]
"""
self._connected = []
self._weights = []

if connections:
for i in connections:
self.connected.append(i[0])
self.weights.append(i[1])

if not uid:
self.id = id(self)
else:
self.id = uid

def __eq__(self, other):
return self.id == other.id

def getConnected(self):
return self._connected

def getWeights(self):
return self._weights

def getConnections(self):
connections = []
for i in range(len(connected)):
connections.append((self._connected[i],self._weight[i]))
return connections

connected = property(getConnected, None)
weights = property (getWeights, None)
connections = property(getConnections, None)

def addConnection(self, node, weight = 0):
self.connected.append(node)
self.weights.append(weight)

def removeConnection(self, node):
i = self._connected.index(node)
del self._connected[i]
del self._weights[i]

#===

Cheers,
Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-21 Thread Gabriel Genellina
En Mon, 21 May 2007 09:26:19 -0300, Unknown <[EMAIL PROTECTED]>  
escribió:

> One example that comes to mind is a class that is a proxy for a database
> class, say Person.
> The Person.Load(id) method doesn't use any instance or class data, it
> instantiates a Person and populates it from the database.
> It is clearly a part of the class's interface so for that I use a
> @staticmethod.

This is called a "factory method" and is usually implemented as a  
classmethod but a staticmethod is often OK.

> *That* Pythonic I'm already ;-)

Good!

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-21 Thread Herman Slagman

"Gabriel Genellina" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
> En Mon, 21 May 2007 07:39:09 -0300, Unknown <[EMAIL PROTECTED]> 
> escribió:
>
>> "Ant" <[EMAIL PROTECTED]> schreef in bericht
>> news:[EMAIL PROTECTED]
>>
>>> Herman has shown you *how* to do static methods in Python, but
>>> typically they are not used. Since Python has first class functions,
>>> and they can be defined at the module level, there is no need to use
>>> static methods.
>>
>> As an experienced developer I'm rather new to Python, so please forgive 
>> me any non-Pythonic babbling.
>>> From a language point you're probably right, but from a design point I'd
>> like to have methods that are clearly associated with a class as methods 
>> of that class, even if they don't use any class or instance related data.
>
> In that case you might want to revise the design, perhaps you carry some 
> preconceptions about how things should be, that are not directly 
> applicable here. (I'm not saying this is related to your specific problem 
> because I don't know exactly what you want, but in general, a lot of 
> design patterns *implementations* are not directly applicable to Python).

I don't really have problems with Python (yet), merely responding to the OPs 
question.

One example that comes to mind is a class that is a proxy for a database 
class, say Person.
The Person.Load(id) method doesn't use any instance or class data, it 
instantiates a Person and populates it from the database.
It is clearly a part of the class's interface so for that I use a 
@staticmethod.

> Modules are objects too - they're a good example of singletons. If you 
> want to create a class containing only static methods: use a module 
> instead. If you want to create a class having a single instance (a 
> singleton), most of the time you can use a module instead.
> Functions don't *have* to be methods in a class, and the resulting design 
> may still be a good design from an OO point of view.

*That* Pythonic I'm already ;-)
For a utility 'class' I'm using a module, no need for a class there.
Using a module for a Singleton is good tip though.

Herman 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-21 Thread Gabriel Genellina
En Mon, 21 May 2007 07:39:09 -0300, Unknown <[EMAIL PROTECTED]>  
escribió:

> "Ant" <[EMAIL PROTECTED]> schreef in bericht
> news:[EMAIL PROTECTED]
>
>> Herman has shown you *how* to do static methods in Python, but
>> typically they are not used. Since Python has first class functions,
>> and they can be defined at the module level, there is no need to use
>> static methods.
>
> As an experienced developer I'm rather new to Python, so please forgive  
> me any non-Pythonic babbling.
>> From a language point you're probably right, but from a design point I'd
> like to have methods that are clearly associated with a class as methods  
> of that class, even if they don't use any class or instance related data.

In that case you might want to revise the design, perhaps you carry some  
preconceptions about how things should be, that are not directly  
applicable here. (I'm not saying this is related to your specific problem  
because I don't know exactly what you want, but in general, a lot of  
design patterns *implementations* are not directly applicable to Python).
Modules are objects too - they're a good example of singletons. If you  
want to create a class containing only static methods: use a module  
instead. If you want to create a class having a single instance (a  
singleton), most of the time you can use a module instead.
Functions don't *have* to be methods in a class, and the resulting design  
may still be a good design from an OO point of view.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-21 Thread Diez B. Roggisch
> 
> Hmm,
> 
> As an experienced developer I'm rather new to Python, so please forgive me
> any non-Pythonic babbling.
> From a language point you're probably right, but from a design point I'd
> like to have methods that are clearly associated with a class as methods
> of that class, even if they don't use any class or instance related data.

Why so? If they _don't_ use that class, whatfor? I use classmethods for
factory-methods. But that at least needs the _class_ as argument somehow,
and grouping it namespace-wise below the class makes sense.

Otherwise, all they do is allowing for java-programming in python - and that
simply because java lacks module level functions.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-21 Thread Herman Slagman

"Ant" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]

> Herman has shown you *how* to do static methods in Python, but
> typically they are not used. Since Python has first class functions,
> and they can be defined at the module level, there is no need to use
> static methods.

Hmm,

As an experienced developer I'm rather new to Python, so please forgive me 
any non-Pythonic babbling.
>From a language point you're probably right, but from a design point I'd 
like to have methods that are clearly associated with a class as methods of 
that class, even if they don't use any class or instance related data.

Herman 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-21 Thread Ant
On May 20, 9:24 pm, Daniel Gee <[EMAIL PROTECTED]> wrote:
...
> The Java version has static methods for common roll styles (XdY and XdY
> +Z) for classes that just want a result but don't want to bother
> keeping an object around for later.
>
> So the question is, assuming that I wanted to keep the static method
> behavior (which I'm not really sure I do), how does one format the
> method header on a 'static' method in Python? Is it just something
> like:
>
> class Foo:
>   def statAdd(self,a):
> return a+5
>
> or do you drop the 'self' bit and just use a 1 variable parameter list?

Herman has shown you *how* to do static methods in Python, but
typically they are not used. Since Python has first class functions,
and they can be defined at the module level, there is no need to use
static methods.

There is a distinction in Python not present in Java between class and
static methods, class methods get the class passed in as the first
parameter, and can be useful if you want a function that acts on data
that the class provides. Static methods in Python are merely normal
functions that are associated with the class - for conceptual reasons
rather than practical ones, and are rarely used as far as I can tell.
I've certainly never bothered with them.

In the case of your statAdd above, self is never used in the method
body, and so this is a clear indication that a module level function
would be more appropriate.

--
Ant...

http://antroy.blogspot.com/


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-21 Thread Herman Slagman

"Daniel Gee" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]

> class Foo:
>  def statAdd(self,a):
>return a+5
>
> or do you drop the 'self' bit and just use a 1 variable parameter list?

class Foo:
 @staticmethod
 def statAdd(a):
   return a+5

HTH

Herman

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-20 Thread Daniel Gee
Alright, sounds good. I'm just not as familiar with the preferred
designs of python.

As to wanting to have them in a class, sometimes I do. Persisting a
roll in a class is only for the slightly more complicated rolls such
as 3d6+5d4-1d12 or "4d6 (drop the lowest and re-roll ones)", things of
that sort.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translating some Java to Python

2007-05-20 Thread Arnaud Delobelle
On May 20, 9:24 pm, Daniel Gee <[EMAIL PROTECTED]> wrote:
> A while ago I wrote a class in Java for all kinds of dice rolling
> methods, as many sides as you want, as many dice as you want, only
> count values above or below some number in the total, things like
> that. Now I'm writing a project in Python that needs to be able to
> make use of that kind of a class.
>
> The Java version has static methods for common roll styles (XdY and XdY
> +Z) for classes that just want a result but don't want to bother
> keeping an object around for later.
>
> So the question is, assuming that I wanted to keep the static method
> behavior (which I'm not really sure I do), how does one format the
> method header on a 'static' method in Python? Is it just something
> like:
>
> class Foo:
>   def statAdd(self,a):
> return a+5
>
> or do you drop the 'self' bit and just use a 1 variable parameter list?

Do you really want your dice rolling functions to be methods?  It
seems to me that you would be better off grouping them as functions in
a module rather than as methods in a class.  A java class full of
static methods translates to a python module populated with functions
in general.

--
Arnaud

-- 
http://mail.python.org/mailman/listinfo/python-list


Translating some Java to Python

2007-05-20 Thread Daniel Gee
A while ago I wrote a class in Java for all kinds of dice rolling
methods, as many sides as you want, as many dice as you want, only
count values above or below some number in the total, things like
that. Now I'm writing a project in Python that needs to be able to
make use of that kind of a class.

The Java version has static methods for common roll styles (XdY and XdY
+Z) for classes that just want a result but don't want to bother
keeping an object around for later.

So the question is, assuming that I wanted to keep the static method
behavior (which I'm not really sure I do), how does one format the
method header on a 'static' method in Python? Is it just something
like:

class Foo:
  def statAdd(self,a):
return a+5

or do you drop the 'self' bit and just use a 1 variable parameter list?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-27 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 bruno at modulix <[EMAIL PROTECTED]> wrote:

>Lawrence D'Oliveiro wrote:
>> In article <[EMAIL PROTECTED]>,
>>  bruno at modulix <[EMAIL PROTECTED]> wrote:
>> 
>> 
>>>Lawrence D'Oliveiro wrote:
>>>
>(snip)
I suppose this is an instance of the more general rule: "using OO when 
you don't have to".
>>>
>>>Lawrence, I'm afraid you're confusing OO with "statically-typed
>>>class-based". FWIW, dynamic typing is part of OO since Smalltalk.
>> 
>> 
>> I wasn't talking about dynamic typing, I was talking about subclassing, 
>> which is very much a part of OO.
>
>What you wrote implies (well, at least I understand it that way) that
>polymorphic dispatch *not* based on subclassing is not OO. Hence my
>reaction : the need to use subclassing (inheritance) for subtyping
>(polymorphic dispatch) is not a requirement of object orientation and
>has never been - it's only a limitation of languages with declarative
>static typing (C++, Java, C# etc).

It's nothing to do with OO, because it's also present in non-OO 
languages.

>> Unless you subscribe to the "OO is whatever looks like a good 
>> programming idea" definition .
>
>Not really !-)

One would hope not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-25 Thread Bruno Desthuilliers
bruno at modulix a écrit :
> Lawrence D'Oliveiro wrote:
> 
>>In article <[EMAIL PROTECTED]>,
>> bruno at modulix <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>>Lawrence D'Oliveiro wrote:
>>>
> 
> (snip)
> 
I suppose this is an instance of the more general rule: "using OO when 
you don't have to".
>>>
>>>Lawrence, I'm afraid you're confusing OO with "statically-typed
>>>class-based". FWIW, dynamic typing is part of OO since Smalltalk.
>>
>>
>>I wasn't talking about dynamic typing, I was talking about subclassing, 
>>which is very much a part of OO.
> 
> 
> What you wrote implies (well, at least I understand it that way)

... but I may just have it totally wrong !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-25 Thread ToddLMorgan
Thanks for those ... just by looking at the colour of the links in my
browser I'd only found 4 of those already so I appreciate the heads up
:- )

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-25 Thread bruno at modulix
Lawrence D'Oliveiro wrote:
> In article <[EMAIL PROTECTED]>,
>  bruno at modulix <[EMAIL PROTECTED]> wrote:
> 
> 
>>Lawrence D'Oliveiro wrote:
>>
(snip)
>>>I suppose this is an instance of the more general rule: "using OO when 
>>>you don't have to".
>>
>>Lawrence, I'm afraid you're confusing OO with "statically-typed
>>class-based". FWIW, dynamic typing is part of OO since Smalltalk.
> 
> 
> I wasn't talking about dynamic typing, I was talking about subclassing, 
> which is very much a part of OO.

What you wrote implies (well, at least I understand it that way) that
polymorphic dispatch *not* based on subclassing is not OO. Hence my
reaction : the need to use subclassing (inheritance) for subtyping
(polymorphic dispatch) is not a requirement of object orientation and
has never been - it's only a limitation of languages with declarative
static typing (C++, Java, C# etc).

> Unless you subscribe to the "OO is whatever looks like a good 
> programming idea" definition .

Not really !-)



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-24 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "Mike Orr" <[EMAIL PROTECTED]> wrote:

>Lawrence D'Oliveiro wrote:
>> "ToddLMorgan" <[EMAIL PROTECTED]> wrote:
>> >Are there python specific equivalents to the common Patterns,
>> >Anti-Patterns and Refactoring books that are so prevalent as
>> >reccomended reading in C++ and Java?
>
>> I don't think they exist. Such books are targeted more towards
>> development in a corporate environment, where every proposal has to go
>> through multiple layers of management, and nothing is ever done by
>> individuals working alone, always by "teams" working on separate parts
>> of the project
>
>Hey, patterns are important.  They keep people from reinventing the
>wheel and banging their head against the wall.

If you have to write more than one piece of code from the same 
"pattern", then that _is_ "reinventing the wheel and banging their head 
against the wall."

The correct way to avoid reinventing the wheel is to reuse code.

For example, in the OO world you hear a good deal about "patterns".
I wonder if these patterns are not sometimes evidence of ...
the human compiler, at work. When I see patterns in my programs, I
consider it a sign of trouble. The shape of a program should reflect
only the problem it needs to solve. Any other regularity in the code
is a sign, to me at least, that I'm using abstractions that aren't
powerful enough

-- Paul Graham 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-24 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 bruno at modulix <[EMAIL PROTECTED]> wrote:

>Lawrence D'Oliveiro wrote:
>> In article <[EMAIL PROTECTED]>,
>>  "ToddLMorgan" <[EMAIL PROTECTED]> wrote:
>> 
>>>I'm looking for the common types of mistakes that say a Java/C# or
>>>even C++ developer may commonly make.
>> 
>> Using subclassing when you don't have to. For instance, you might have a 
>> Java method which takes an argument of type java.io.OutputStream to 
>> which it writes. You might translate this to a Python method to which 
>> you are careful to only pass instances of subclasses of file objects. 
>> But in fact there is no necessity for this: you are free to pass any 
>> object which has appropriate members.
>> 
>> I suppose this is an instance of the more general rule: "using OO when 
>> you don't have to".
>
>Lawrence, I'm afraid you're confusing OO with "statically-typed
>class-based". FWIW, dynamic typing is part of OO since Smalltalk.

I wasn't talking about dynamic typing, I was talking about subclassing, 
which is very much a part of OO.

Unless you subscribe to the "OO is whatever looks like a good 
programming idea" definition .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-24 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "gene tani" <[EMAIL PROTECTED]> wrote:

>http://www.ferg.org/projects/python_gotchas.html

Amazing. Backslashes are listed as not one, but _two_ items on the list.

The problem is not with Python at all, it is with the MS-DOS foundations 
of Windows. When directory hierarchies were added in DOS 2.0, they used 
the wrong character, "\" instead of "/", as the directory separator.

I call this "DOSLexia", and it has afflicted DOS/Windows users ever 
since.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-24 Thread Mike Orr
Lawrence D'Oliveiro wrote:
> "ToddLMorgan" <[EMAIL PROTECTED]> wrote:
> >Are there python specific equivalents to the common Patterns,
> >Anti-Patterns and Refactoring books that are so prevalent as
> >reccomended reading in C++ and Java?

> I don't think they exist. Such books are targeted more towards
> development in a corporate environment, where every proposal has to go
> through multiple layers of management, and nothing is ever done by
> individuals working alone, always by "teams" working on separate parts
> of the project

Hey, patterns are important.  They keep people from reinventing the
wheel and banging their head against the wall.  Perhaps the best source
for Python patterns is the Python Cookbook.
http://www.oreilly.com/catalog/pythoncook/
http://aspn.activestate.com/ASPN/Python/Cookbook/
I recommend at least going through the table of contents so you'll know
where to go when you're wondering, "How do I do X in Python?"

--Mike

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-24 Thread Harry George
Lawrence D'Oliveiro <[EMAIL PROTECTED]> writes:

> In article <[EMAIL PROTECTED]>,
>  "ToddLMorgan" <[EMAIL PROTECTED]> wrote:
> 
> >Are there python specific equivalents to the common Patterns,
> >Anti-Patterns and Refactoring books that are so prevalent as
> >reccomended reading in C++ and Java?
> 
> I don't think they exist. Such books are targeted more towards 
> development in a corporate environment, where every proposal has to go 
> through multiple layers of management, and nothing is ever done by 
> individuals working alone, always by "teams" working on separate parts 
> of the project. And also where the end-users don't really get much say 
> in how things are supposed to work. It's only in such a high-overhead, 
> top-down, cover-your-ass environment that such books are looked on as 
> being at all useful. Possibly on the grounds that nobody ever got fired 
> for buying them.
> 
> I'd say languages like Python and Perl are the absolute antithesis of 
> this sort of development culture.

On "antithesis" comment:

Python can be used for Agile Programming, with the end user there at
the monitor.  But it can also be used for heavy duty development
regimens with data models, specifications, development teams working
multiple shifts or working worldwide, separate test-and-release teams,
etc.

On response to the OP:

The most important thing you bring to the table is knowledge of data
formats, algorithms, OO programming, and test-driven design. E.g.,
XML, HTML, LDAP, SQL, pipes, stacks, queues, threads, dictionaries,
lexers, parsers, regular expressions, matrix transformations, GUI
dialogs, etc.  Many of us consider Python a secret weapon in learning
new paradigms and technologies

The most important things you need to leave behind:

1.  Intuition about what is already available vs what you have to
write.  Java tries to reinvent the whole compsci world.  Python just
says "Nice C/C++/FORTRAN library; I think I'll use it via a binding."
If it is codable, it is probably scriptable in Python.

2. Temptation to reinvent entire stacks of libraries to replicate the
Java module import structure.  This is a real problem in migrating
existing code.  You have to take deep breath and ask "What is the
fundamental task, and how would a programmer do that in Python?"
Entire library trees melt away when you do this.

3. Fear you are missing something when you get done.  Python takes
c. 1/3 as many LOC as Java for the same task. At first I kept saying:
"This wee bit of code couldn't posssibly do the whole job, could it?"
If you have a good regression test suite, you are done when it works.
If you need help getting on board unittests, see mkpythonproj:
http://www.seanet.com/~hgg9140/comp/index.html#L006


-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-24 Thread gene tani

Ant wrote:
> Take a look at the newgroup archives over the last week or two - there
> seem to have been a glut of people coming from Java to Python and
> asking the same sort of questions. There were some links to a bunch of
> Python 'gotcha' pages which will be useful.
>

Here's a few gotchas which i would like to drop into the python wiki,
but I couldn't find an appropriate place.  Maybe the Intermediate
Conundrums page?
Anyway, if OP take the time to flip through these, it'll speed the
learning, I hope.

http://www.ferg.org/projects/python_gotchas.html
http://zephyrfalcon.org/labs/python_pitfalls.html
http://zephyrfalcon.org/labs/beginners_mistakes.html
http://www.python.org/doc/faq/
http://wiki.python.org/moin/Intermediate_Conundrums

http://diveintopython.org/appendix/abstracts.html
http://diveintopython.org/appendix/tips.html

http://blog.ianbicking.org/my-python-4k.html

http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html
http://www.norvig.com/python-iaq.html
http://www.faqts.com/knowledge_base/index.phtml/fid/245

http://amk.ca/python/writing/warts
http://c2.com/cgi/wiki?PythonProblems

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-24 Thread bruno at modulix
Lawrence D'Oliveiro wrote:
> In article <[EMAIL PROTECTED]>,
>  "ToddLMorgan" <[EMAIL PROTECTED]> wrote:
> 
> 
>>I'm looking for the common types of mistakes that say a Java/C# or
>>even C++ developer may commonly make.
> 
> 
> Using subclassing when you don't have to. For instance, you might have a 
> Java method which takes an argument of type java.io.OutputStream to 
> which it writes. You might translate this to a Python method to which 
> you are careful to only pass instances of subclasses of file objects. 
> But in fact there is no necessity for this: you are free to pass any 
> object which has appropriate members.
> 
> I suppose this is an instance of the more general rule: "using OO when 
> you don't have to".

Lawrence, I'm afraid you're confusing OO with "statically-typed
class-based". FWIW, dynamic typing is part of OO since Smalltalk.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-23 Thread ToddLMorgan
I've actually managed to find some other links by backtracking through
some of the links that you provided.

The most comprehensive so far is this one
http://www.razorvine.net/python/PythonForJavaProgrammers and a summary
version (on the same site)
http://www.razorvine.net/python/PythonComparedToJava

The site owner (Irmen de Jong) appears to be be compiling a decent
migration path from Java to Python on a Moin-Moin Wiki so perhaps he'll
be harvesting more useful information from here and other places in the
near future as the pages only appears a few days ago.

There was also a follow up to
http://naeblis.cx/rtomayko/2004/12/15/the-static-method-thing  with
http://naeblis.cx/rtomayko/2005/01/20/getters-setters-fuxors

Hopefully this will prove helpful to some other folks :- )

I'm still working my way up to the practice sites (python and math
challenge) ... I want to do a bit more reading first :- )

ciao & thanks
 Todd

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Ant
Take a look at the newgroup archives over the last week or two - there
seem to have been a glut of people coming from Java to Python and
asking the same sort of questions. There were some links to a bunch of
Python 'gotcha' pages which will be useful.

For my part, I came from Java to Python, and found that it was useful
to do a load of small  scripts in the simplest way possible, or in as
many different ways possible. For example, trying a script involving
creating a new iterable object from a list using for loops, list
comprehensions, generators or functional built-ins (such as map()). The
clearest method usually seems to be considered the most pythonic.

A couple of sites to practice against are:
http://www.pythonchallenge.com/
http://mathschallenge.net/

They give a good set of problems which will work various aspects of
Python that aren't familiar to Java guys, and also break the mindset
that everything has to be done in classes.

I'm still making the transition of course ;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Chris Lambacher

http://dirtsimple.org/2004/12/python-is-not-java.html
http://dirtsimple.org/2004/12/java-is-not-python-either.html
http://dirtsimple.org/2004/12/python-interfaces-are-not-java.html

This link seems to be down at the moment.
http://naeblis.cx/rtomayko/2004/12/15/the-static-method-thing

The above articles were really helped me understand the python way of doining
things.  In particular they mention language features that may be named the
same and do similar things, but would be used for totally different reasons in
the two languages.

I hope you find them as helpful as I did.

-Chris


On Sat, Apr 22, 2006 at 12:40:51AM -0700, ToddLMorgan wrote:
> I'm just starting out with python, after having a long history with
> Java. I was wondering if there were any resources or tips from anyone
> out there in Python-land that can help me make the transition as
> successfully as possible? Perhaps you've made the transition yourself
> or just have experience with folks who have made the transition.
> 
> I'm looking for the common types of mistakes that say a Java/C# or
> even C++ developer may commonly make. More examples like those
> highlighted here http://dirtsimple.org/2004/12/python-is-not-java.html
> would be particularly useful. I've already made the static class
> method mistake, and been thoroughly confused by packages and
> imports/froms and extremely frustrated with attempting to call super
> constructors etc.  I'm getting the hang of passing around functions
> (ala the command pattern), customising the operators and extending
> inbuilt classes. All of these concepts I've done before so there
> nothing really great and wonderful about using them in another
> language. Some of the really powerful ideas of python (eg as suggested
> in the link) about creating one function containing a template function
> that can cater to all possible implementations sounds really cool and
> alien to me at the same time. That's the sort of stuff I'm
> interested in.
> 
> At this point in time I'd say my python code is more coding Java in
> python than doing it in a pythonic way. Perhaps there some good/great
> examples of Python scripts or projects that I could look at to get
> inspired or learn pythonic implementation ideas? I just don't know of
> any. Are there python specific equivalents to the common Patterns,
> Anti-Patterns and Refactoring books that are so prevalent as
> reccomended reading in C++ and Java? If so what?
> 
> Given the rising popularity of Python these days there has got to be a
> few of you out there who've made the transition successfully and have
> some pearls-of-wisdom to share that you'd wished you'd known about
> earlier.
> 
> Thanks
>  Todd
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Anton Vredegoor
ToddLMorgan wrote:

> I'm just starting out with python, after having a long history with
> Java. I was wondering if there were any resources or tips from anyone
> out there in Python-land that can help me make the transition as
> successfully as possible? Perhaps you've made the transition yourself
> or just have experience with folks who have made the transition.

Some time ago I had to learn a bit of Java in order to be able to write 
some signed jython browser applets that I could use while working at a 
highly restricted public library computer. So I guess I was coming from 
the opposite direction :-) Anyway I wondered why (and how!) very small 
jython scripts could replace large blocks of java code.

Maybe looking at it from a jython perspective will be educational for 
you. I think it would be a lot of fun realizing how much java code can 
actually be 'automatically' generated or filled in by jython traversing 
its class system.

Also I'm hoping it would produce an opportunity for an advanced java 
coder to write some cool signed java applet in jython that would have 
the look and feel of idle.py for python but that would run from a 
webbrowser.

I know it can be done because I did write some experimental but still 
already very functional things like a jython console webbrowser applet, 
a websucker.py running from within a browser, and I hacked some other
jython editor-console (eclipse is good for such things) to add some 
functionality and do my own signing and library selection.

Don't ask for my code yet though, it's nowhere near presentable. Anyway, 
since then I found a job that gives me access to less locked down 
computers which is also fun.

Anton

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "ToddLMorgan" <[EMAIL PROTECTED]> wrote:

>Are there python specific equivalents to the common Patterns,
>Anti-Patterns and Refactoring books that are so prevalent as
>reccomended reading in C++ and Java?

I don't think they exist. Such books are targeted more towards 
development in a corporate environment, where every proposal has to go 
through multiple layers of management, and nothing is ever done by 
individuals working alone, always by "teams" working on separate parts 
of the project. And also where the end-users don't really get much say 
in how things are supposed to work. It's only in such a high-overhead, 
top-down, cover-your-ass environment that such books are looked on as 
being at all useful. Possibly on the grounds that nobody ever got fired 
for buying them.

I'd say languages like Python and Perl are the absolute antithesis of 
this sort of development culture.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "ToddLMorgan" <[EMAIL PROTECTED]> wrote:

>I'm looking for the common types of mistakes that say a Java/C# or
>even C++ developer may commonly make.

Using subclassing when you don't have to. For instance, you might have a 
Java method which takes an argument of type java.io.OutputStream to 
which it writes. You might translate this to a Python method to which 
you are careful to only pass instances of subclasses of file objects. 
But in fact there is no necessity for this: you are free to pass any 
object which has appropriate members.

I suppose this is an instance of the more general rule: "using OO when 
you don't have to".
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for resources for making the jump from Java to Python easier and more productive

2006-04-22 Thread ToddLMorgan
I'm just starting out with python, after having a long history with
Java. I was wondering if there were any resources or tips from anyone
out there in Python-land that can help me make the transition as
successfully as possible? Perhaps you've made the transition yourself
or just have experience with folks who have made the transition.

I'm looking for the common types of mistakes that say a Java/C# or
even C++ developer may commonly make. More examples like those
highlighted here http://dirtsimple.org/2004/12/python-is-not-java.html
would be particularly useful. I've already made the static class
method mistake, and been thoroughly confused by packages and
imports/froms and extremely frustrated with attempting to call super
constructors etc.  I'm getting the hang of passing around functions
(ala the command pattern), customising the operators and extending
inbuilt classes. All of these concepts I've done before so there
nothing really great and wonderful about using them in another
language. Some of the really powerful ideas of python (eg as suggested
in the link) about creating one function containing a template function
that can cater to all possible implementations sounds really cool and
alien to me at the same time. That's the sort of stuff I'm
interested in.

At this point in time I'd say my python code is more coding Java in
python than doing it in a pythonic way. Perhaps there some good/great
examples of Python scripts or projects that I could look at to get
inspired or learn pythonic implementation ideas? I just don't know of
any. Are there python specific equivalents to the common Patterns,
Anti-Patterns and Refactoring books that are so prevalent as
reccomended reading in C++ and Java? If so what?

Given the rising popularity of Python these days there has got to be a
few of you out there who've made the transition successfully and have
some pearls-of-wisdom to share that you'd wished you'd known about
earlier.

Thanks
 Todd

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-07 Thread bruno at modulix
[EMAIL PROTECTED] wrote:

(snip)

> Does anyone here have any experience with large(ish) webapps in Python?

Depends on the definition of "large(ish)". If you use KLOC as a metric,
you can expect a Python solution to be 5 to 10 time smaller, so what's a
'large' app in Java may end up as a small/medium app with Python !-)

> I was sniffing around the following A-team of toolkits: CherryPy,
> Cheetah, SQLObject, all behind Apache2. 

If you plan to run behind Apache2, you may want to have a look at
Myghty. It's somewhere between a framework and a templating system, and
the architecture is based on Perl's HTML::Mason, which has proven to be
successful. It adds to Mason the possibility to take a clean MVC
approach (as well as the more ServerPage oriented approach of Mason),
and can be deployed as either a mod_python handler, fastcgi, plain old
cgi, WSGI, and even as a standalone app (with a Python HTTPServer) for
developpement.

You may also want to take a look at Turbogears (CherryPy + SQLObject +
Kid + Mochikit) or Subway (CherryPy + SQLObject + Cheetah).


> Has anyone seen performance
> issues with Python webapps?

Actually, only with Plone or CPS (or other ZopeCMF based app). Zope
itself is pretty usable, but the whole CMF part is a monstruosity IMHO.

> Could one reasonably expect to have an easier time with maintainence
> and future modifications with using Python over Java?

Err... It of course depends on first having well written code and a
sensible design, but when it comes to agility - and as long as you stay
away from Zope's CMF !-) -, I bet that Python beats Java hands down.

> Any tips, stories, recommendations, and/or experiences are most
> welcome.

It took me about one month to write my first Zope application - an
ad-hoc mix of an online catalog and basic CMS (pages, news,
downloadables files, ...), with LDAP and PostgresSQL in the mix,
fulltext and advanced search, newsletter subscription, a 'members' zone
etc. I had to learn Zope during the process, and I guess I could
actually rewrite the whole thing in less than 2 weeks with a much better
design - but what, the app is in production for 2 years with near zero
corrective maintenance (the biggest problem we had was with system
updates messing with the psycopg adapter...), gives full satisfaction to
the customer, and has for now proven to be  very easy to modify and
evolve (so easy that we didn't even bothered to bill the customer for
much of the modification requests)...  And Zope is certainly not known
as the most agile or lightweight Python web framework/application server !-)



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-06 Thread George Sakkis
> Any tips, stories, recommendations, and/or experiences are most
> welcome.

Just one suggestion, read the article "Things You Should Never Do, Part
I" first (
http://www.joelonsoftware.com/articles/fog69.html). Quoting
from the article:

(Netscape made) "the *single worst strategic mistake* that any software
company can make: They decided to rewrite the code from scratch."

As much as I find python more maintenable and fun to work with in the
long run, I would be *very hesitant* to start a complete rewrite,
especially given the insufficient documentation of your webapp and your
lack of experience with a pythonic web framework.

George

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-06 Thread Fabio Zadrozny
Kent Johnson wrote:

>Fabio Zadrozny wrote:
>  
>
>>I agree that python code is usually smaller... but what you did is too 
>>unfair (the code below would be more suitable for the comparrison).
>>
>>python:
>>print "%10.2f" % 10
>>
>>java:
>>System.out.println(String.format("%10.2f", 10.0));
>>
>>
>
>Though String.format() is new in Java 1.5 so in older code or for 
>backward compatibility the longer code may be found. OTOH Python has 
>supported % formatting since at least version 1.4 released in 1996.
>http://www.python.org/doc/1.4/lib/node11.html#SECTION00315100
>
>In my experience the original point is valid - Python is usually 
>(always?) more concise than equivalent Java code, and often dramatically 
>so. Python makes common operations easy; Java sometimes seems to go out 
>of its way to make them awkward.
>
>Kent
>  
>

Yeap, I agree with the original point too (as I explained in the rest of 
my comment)... just didn't think it was a 'fair' comparisson. ;-)
-- me? When I use java I write 1.5 code and 'retroweave' it to be 
compatible with java 1.4 (Pydev is done this way) -- and I use Python at 
work -- and I'm very happy with it... I just think that a language is as 
a tool, and each may be suited better for a different occasion.

The 'usually smaller' I mentioned is because sometimes java code gets 
smaller because of the already-existing codebase... E.g.: for developing 
an IDE, Eclipse already has a huge codebase, so, if I wanted to do all 
that was already done in it in python just because Eclipse was in java, 
I think I would be doing the wrong decision, and besides, I could use 
jython for it if I wanted to...

And from what I understood, the original poster had a large codebase in 
java already, so, I'm not sure that changing  everything to python would 
be the way to go (altough that DOES depend a lot on the original 
codebase quality).

Cheers,

Fabio

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

PyDev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-06 Thread Kent Johnson
Fabio Zadrozny wrote:
> I agree that python code is usually smaller... but what you did is too 
> unfair (the code below would be more suitable for the comparrison).
> 
> python:
> print "%10.2f" % 10
> 
> java:
> System.out.println(String.format("%10.2f", 10.0));

Though String.format() is new in Java 1.5 so in older code or for 
backward compatibility the longer code may be found. OTOH Python has 
supported % formatting since at least version 1.4 released in 1996.
http://www.python.org/doc/1.4/lib/node11.html#SECTION00315100

In my experience the original point is valid - Python is usually 
(always?) more concise than equivalent Java code, and often dramatically 
so. Python makes common operations easy; Java sometimes seems to go out 
of its way to make them awkward.

Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-06 Thread Fabio Zadrozny
I agree that python code is usually smaller... but what you did is too 
unfair (the code below would be more suitable for the comparrison).

python:
print "%10.2f" % 10

java:
System.out.println(String.format("%10.2f", 10.0));

-- altough for me it would be the same, as I have defined a print 
method... so, it is always something as:
print ("%10.2f", 10) in java for me :-)

What I'm trying to say here is that if you already have a big java app, 
sometimes spending some time trying to refactor it for better 
understanding is more useful than scrapping what already exists 
(especially if you have good test cases)... altough I would reccomend 
jython for new development on that same application.

I guess that the main difference is that python usually makes you do the 
right thing, whereas in java you need to know a lot more about it to 
manage to do the right thing...

Cheers,

Fabio

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

PyDev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com




Giovanni Bajo wrote:

>John M. Gabriele wrote:
>
>  
>
>>>But once it is
>>>there, Python is a good choice for web apps. Java is slow
>>>  
>>>
>>Slow? They're both dynamic languages, but Java is statically
>>typed (with less work to do at runtime). For long-running processes,
>>I'd guess that Java bytecode executes faster than Python bytecode.
>>
>>
>
>
>It's not the raw computing performance that counts in this case. I got this
>joke in my mail today:
>
>Python:
>print "%10.2f" % x
>
>Java:
>java.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance();
>formatter.setMinimumFractionDigits(2);
>formatter.setMaximumFractionDigits(2);
>String s = formatter.format(x);
>for (int i = s.length(); i < 10; i++) System.out.print(' ');
>System.out.print(s);
>
>Let alone the time it takes to write this routine, I'm hundered percent sure
>that the Python's version is also faster at runtime. Python lets you write
>pretty expressive code which is easy to maintain and where the computation cost
>is easily at the C level. Also Python code is pretty bare-metal, so that
>file.write or socket.write go to the syscall immediately. Try that in Java and
>you'll find 30 layers of complex abstractions for doubtful benefits and obvious
>slowness.
>  
>


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-05 Thread AdSR
Giovanni Bajo wrote:
> Also Python code is pretty bare-metal, so that
> file.write or socket.write go to the syscall immediately. Try that in Java and
> you'll find 30 layers of complex abstractions for doubtful benefits and 
> obvious
> slowness.

+1 QOTW
(I'd recommend the whole post but it might be too long.)

Cheers,

AdSR

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-04 Thread John M. Gabriele
Shalabh Chaturvedi wrote:
> [EMAIL PROTECTED] wrote:
> 
> A class-to-class and method-to-method rewrite will give some but likely 
> not the full benefit of moving to Python. A redesign might be necessary 
> - making it more 'Pythonic' in the process. In my experience, many cruft 
> classes that exist in a Java design simply disappear when ported to 
> Python. See also http://dirtsimple.org/2004/12/python-is-not-java.html
> 
> Cheers,
> Shalabh
> 

Great link Shalabh. Thanks. :) Googling around, I'd also come across
that one.

---J

-- 
(remove zeez if demunging email address)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-04 Thread Shalabh Chaturvedi
[EMAIL PROTECTED] wrote:
> I've got a fairly substantial webapp written in Java (plus Tomcat,
> Hibernate, Struts, JSP, MySQL) that is a bit of a bear to work with. I
> didn't write it. Much of it is only very sparsely documented (if at
> all). No design docs anywhere. It's a large webapp with many classes
> and fairly deep inheritance hierarchies. There seems to be JUnit test
> cases in place.
> 
> The possibility of re-writing it has come up, and I must say that,
> although it would likely be a ton of work, it could also be a real
> pythonic adventure. ;) 

> Any tips, stories, recommendations, and/or experiences are most
> welcome.
> 

A class-to-class and method-to-method rewrite will give some but likely 
not the full benefit of moving to Python. A redesign might be necessary 
- making it more 'Pythonic' in the process. In my experience, many cruft 
classes that exist in a Java design simply disappear when ported to 
Python. See also http://dirtsimple.org/2004/12/python-is-not-java.html

Cheers,
Shalabh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-04 Thread Giovanni Bajo
John M. Gabriele wrote:

>> But once it is
>> there, Python is a good choice for web apps. Java is slow
>
> Slow? They're both dynamic languages, but Java is statically
> typed (with less work to do at runtime). For long-running processes,
> I'd guess that Java bytecode executes faster than Python bytecode.


It's not the raw computing performance that counts in this case. I got this
joke in my mail today:

Python:
print "%10.2f" % x

Java:
java.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String s = formatter.format(x);
for (int i = s.length(); i < 10; i++) System.out.print(' ');
System.out.print(s);

Let alone the time it takes to write this routine, I'm hundered percent sure
that the Python's version is also faster at runtime. Python lets you write
pretty expressive code which is easy to maintain and where the computation cost
is easily at the C level. Also Python code is pretty bare-metal, so that
file.write or socket.write go to the syscall immediately. Try that in Java and
you'll find 30 layers of complex abstractions for doubtful benefits and obvious
slowness.
-- 
Giovanni Bajo


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-04 Thread Scott David Daniels
John M. Gabriele wrote:
> [EMAIL PROTECTED] wrote:
>> But once it is
>> there, Python is a good choice for web apps. Java is slow
> 
> Slow? They're both dynamic languages, but Java is statically
> typed (with less work to do at runtime). For long-running processes,
> I'd guess that Java bytecode executes faster than Python bytecode.

Well, perhaps yes, but not so if you count the fact that recoding
is so easy that you can race several implementations of the same
thing to see which trade-offs work.  Java may run the one algorithm
you decide to write faster than Python will run the same thing,
but in Python you may race five algorithms and keep the fastest.
Using programmer resources effectively is Python's secret sauce.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-03 Thread John M. Gabriele
[EMAIL PROTECTED] wrote:
> To replace a large framework you will probably need a framework.

Well, I'm sure not all web frameworks are created equal, however,
CherryPy does bill itself as a "web framework".

> Take a
> look at http://www.djangoproject.com or http://www.turbogears.org. They
> both use some of the tools you mention but operate on a higher level.

Django looks interesting to me. Would like to try out mod_python.
Taking a look...

> I find Python fairly easy to maintain. Unfortunatly, I do not find it
> easy to take a bunch of Java code and move it to Python.

Well, I figured it might be better to use the previous webapp
as a *model* to learn from, rather than to directly translate
code from Java to Python.

> But once it is
> there, Python is a good choice for web apps. Java is slow

Slow? They're both dynamic languages, but Java is statically
typed (with less work to do at runtime). For long-running processes,
I'd guess that Java bytecode executes faster than Python bytecode.

> and has a big
> footprint.

Yes.

> Python is reasonably nimble and good design choices pay off.
> Plus, you must write many more lines of Java to do what you can in
> Python.

Yup. The main issue with the current Java webapp seems to be
that it takes a long time to make changes/additions.

> I do not know the code you are not working with, but a lot of
> large Java apps can be poorly written.

I've found that good documentation is *most* critical. At least
if the docs are good, but the code needs work, you have some
direction as to how to fix the code. If there's no docs, you
spend hours wondering why things are done the way they're done.

Currently having a look at the Django docs. :)

Thanks Brian!
---J
-- 
(remove zeez if demunging email address)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fairly large webapp: from Java to Python. experiences?

2006-02-03 Thread [EMAIL PROTECTED]
To replace a large framework you will probably need a framework. Take a
look at http://www.djangoproject.com or http://www.turbogears.org. They
both use some of the tools you mention but operate on a higher level.

I find Python fairly easy to maintain. Unfortunatly, I do not find it
easy to take a bunch of Java code and move it to Python. But once it is
there, Python is a good choice for web apps. Java is slow and has a big
footprint. Python is reasonably nimble and good design choices pay off.
Plus, you must write many more lines of Java to do what you can in
Python. I do not know the code you are not working with, but a lot of
large Java apps can be poorly written.

I guess you could also look at http://www.jython.org/ and see if you
can somehow make the transition but not all at once.

Good luck,


-- 
http://mail.python.org/mailman/listinfo/python-list


fairly large webapp: from Java to Python. experiences?

2006-02-03 Thread john_sips_tea
I've got a fairly substantial webapp written in Java (plus Tomcat,
Hibernate, Struts, JSP, MySQL) that is a bit of a bear to work with. I
didn't write it. Much of it is only very sparsely documented (if at
all). No design docs anywhere. It's a large webapp with many classes
and fairly deep inheritance hierarchies. There seems to be JUnit test
cases in place.

The possibility of re-writing it has come up, and I must say that,
although it would likely be a ton of work, it could also be a real
pythonic adventure. ;) Reasons for a rewrite are to get better
flexibility, easier maintenance (easier to make changes), and the
possibility of really slimming down the size of the thing. And of
course, it would be nice to work with Python -- possibly significantly
more productive.

Does anyone here have any experience with large(ish) webapps in Python?
I was sniffing around the following A-team of toolkits: CherryPy,
Cheetah, SQLObject, all behind Apache2. Has anyone seen performance
issues with Python webapps?

Could one reasonably expect to have an easier time with maintainence
and future modifications with using Python over Java?

Any tips, stories, recommendations, and/or experiences are most
welcome.

Thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Java to Python - how to??

2005-06-13 Thread George Sakkis
[EMAIL PROTECTED] wrote:

> Hello
>
> I just start programing in Python.
> I've got a qestion, how translate the example code writen in Java to
> Python??
>
>
> public class ConnectionManager {
>
>   public ConnectionManager() {
> super();
>   }
>   public void sendAgent(Agent anAgent, WorkplaceAddress anAddress) {
>
>   }
> }
>
> bye


class ConnectionManager(object):

def __init__(self):
super(ConnectionManager,self).__init__()
  
def sendAgent(self, anAgent, anAddress):
pass


George

-- 
http://mail.python.org/mailman/listinfo/python-list


Java to Python - how to??

2005-06-13 Thread ka_czor
Hello

I just start programing in Python.
I've got a qestion, how translate the example code writen in Java to
Python?? 


public class ConnectionManager {

  public ConnectionManager() {
super();
  }
  public void sendAgent(Agent anAgent, WorkplaceAddress anAddress) {

  }
}

bye 
-- 
http://mail.python.org/mailman/listinfo/python-list