From: Anthony E. <ae...@si...> - 2002-03-26 18:23:08
|
Currently, in Jython, using any arbitrary Java object aside from a java.lang.String, the following fails: print "text" + obj With the message: TypeError: __add__ nor __radd__ defined for these operands But the following works: print "test", obj Would the Jython implementers consider modifying the PyJavaInstance class with something similar to: public PyObject __add__(PyObject object) { return __str__ + object.__str__(); } So that the + notation as used in Java works properly? I am not sure if the code I provided above is correct as I am not intimately familiar with the Jython source. I am also not sure if this has been discussed before: the mailing list archives provided at the Jython.org site do not have search facilities (AFAICT) and I was unable to find anything about it in my mail application (back to 7/21/2001), so I apologize ahead of time if it has. Sincerely, Anthony Eden |
From: Kevin B. <kb...@ca...> - 2002-03-26 18:52:20
|
I'd be hesitant to do this. A couple of reasons: - In general, the Python string formatting idioms are preferred: Instead of: print "text " + obj + ", " + obj2 + "/" + obj3 use: print "text %s, %s/%s" % (obj, obj2, obj3) or: print "text %(obj)s, %(obj2)s/%(obj3)s" % vars() - The proposed enhancement for Java instances would cause Python instances & java instances to behave differently: t = 5 s = Object() print "text" + t + " " + s ## error kb Anthony Eden wrote: > Currently, in Jython, using any arbitrary Java object aside from a java.lang.String, the following fails: > > print "text" + obj > > With the message: TypeError: __add__ nor __radd__ defined for these operands > > But the following works: > > print "test", obj > > > Would the Jython implementers consider modifying the PyJavaInstance class with something similar to: > > public PyObject __add__(PyObject object) { > return __str__ + object.__str__(); > } > > So that the + notation as used in Java works properly? I am not sure if the code I provided above is correct as I am > not intimately familiar with the Jython source. I am also not sure if this has been discussed before: the mailing list > archives provided at the Jython.org site do not have search facilities (AFAICT) and I was unable to find anything about > it in my mail application (back to 7/21/2001), so I apologize ahead of time if it has. > > Sincerely, > Anthony Eden > > > _______________________________________________ > Jython-users mailing list > Jyt...@li... > https://lists.sourceforge.net/lists/listinfo/jython-users |
From: Samuele P. <pe...@in...> - 2002-03-26 19:14:11
|
From: Kevin Butler <kb...@ca...> > - The proposed enhancement for Java instances would cause Python instances & java instances to behave differently: > t = 5 > s = Object() > print "text" + t + " " + s ## error > Exactly, that's the point, as long as Jython is an implementation of Python <wink> , the behavior + and strings will not change, sorry. regards. |
From: Anthony E. <ae...@si...> - 2002-03-26 19:24:55
|
No need to be sorry. Thanks to all who have answered this to clear this up and for demonstrating the proper way to handle String concatenation in Jython. Perhaps this should be added to the FAQ. ;-) For Java programmers getting into Python via Jython, the behavior is not evident. Sincerely, Anthony Eden > -----Original Message----- > From: Samuele Pedroni [mailto:pe...@in...] > Sent: Tuesday, March 26, 2002 2:13 PM > To: kb...@ca...; Anthony Eden > Cc: jyt...@li... > Subject: Re: [Jython-users] Supporting + on Java objects > > > From: Kevin Butler <kb...@ca...> > > > - The proposed enhancement for Java instances would cause Python instances & > java instances to behave differently: > > t = 5 > > s = Object() > > print "text" + t + " " + s ## error > > > > Exactly, that's the point, as long as Jython is an implementation > of Python <wink> , the behavior + and strings will not change, sorry. > > regards. > > |
From: Doug L. <lan...@go...> - 2002-03-26 20:10:54
|
At 2:24 PM -0500 3/26/02, Anthony Eden wrote: >No need to be sorry. Thanks to all who have answered this to clear this up and for demonstrating the proper way to >handle String concatenation in Jython. Perhaps this should be added to the FAQ. ;-) For Java programmers getting into >Python via Jython, the behavior is not evident. All such programmers should read Tim Peters' "Zen of Python" at least once a month until it sinks in... http://www.python.org/doc/Humor.html#zen It's short enough to include here in its entirety (see below). Brad Cox wrote: > The token (+ vs , vs nothing) isn't important. What *is* is > that the result winds up as a string, not array, tuple, etc. ... which implies that there is a possible ambiguity. So, for Jython to guess what you meant, it would have to break *two* of the Zen suggestions: Explicit is better than implicit. In the face of ambiguity, refuse the temptation to guess. I think one of these at a time is occasionally broken for a good enough cause, but two? Let's just say I don't think it'll happen soon. The workaround is painless enough -- and more explicit. -- Doug PS, here's Tim's text: The Zen of Python (by Tim Peters) Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! |
From: Anthony E. <ae...@si...> - 2002-03-26 20:50:39
|
FWIW, the text below would make a good FAQ entry for Java programmers coming to the world of Python wondering about how Strings work in Python. Kevin's explanation was right on track and answered the question succinctly. I am sure that String concatenation is covered in the Python docs, but I still think it would be good to cover this in the Jython docs, primarily because a lot of Java code transfers very easily to Python but some of it (such as for(x in y) and String handling) do not. Perhaps there are other stumbling blocks which Java developers coming to Jython will experience which could also be documented better on the Jython site. What do you think? Sincerely, Anthony Eden > -----Original Message----- > From: jyt...@li... > [mailto:jyt...@li...]On Behalf Of Kevin > Butler > Sent: Tuesday, March 26, 2002 1:53 PM > To: Anthony Eden > Cc: jyt...@li... > Subject: Re: [Jython-users] Supporting + on Java objects > > <snip> > > - In general, the Python string formatting idioms are preferred: > Instead of: > print "text " + obj + ", " + obj2 + "/" + obj3 > use: > print "text %s, %s/%s" % (obj, obj2, obj3) > or: > print "text %(obj)s, %(obj2)s/%(obj3)s" % vars() > |
From: Brad C. <bc...@vi...> - 2002-03-26 19:31:27
|
As the one that asked Anythony about this (mis?)feature on the jpublish list, I'd like to add my support to his request. I'd have done it directly except that I'm so new to python that I'd thought this was my fault. PS: The token (+ vs , vs nothing) isn't important. What *is* is that the result winds up as a string, not array, tuple, etc. PPS: Probably harder, supporting expansion of variables within strings ala' perl would immediately make python a favorite. The ${variable}s workaround that was offered here earlier is a bit obscure for heavily used stuff like expanding variable information into html template files. See http://virtualschool.edu/jwaa under Mls (multi line preprocessor), velocity, or JSP/ASP for workarounds to the same problem in Java. This really "should" be supported by the language, not outside as in mls, velocity, or jsp. Like this: title = "my title" print ''' <html> <head> <title>$title</title> </head> </html> ''' Ideally, this should work for any expression (variables, subroutine calls, arrays, tuples, etc). As I recall, perl didn't do all of these right. Don't recall exactly; I haven't used perl in some years. At 1:23 PM -0500 3/26/02, Anthony Eden wrote: >Currently, in Jython, using any arbitrary Java object aside from a >java.lang.String, the following fails: > > print "text" + obj > >With the message: TypeError: __add__ nor __radd__ defined for these operands > >But the following works: > > print "test", obj > >Would the Jython implementers consider modifying the PyJavaInstance >class with something similar to: > > public PyObject __add__(PyObject object) { > return __str__ + object.__str__(); > } > >So that the + notation as used in Java works properly? I am not >sure if the code I provided above is correct as I am >not intimately familiar with the Jython source. I am also not sure >if this has been discussed before: the mailing list >archives provided at the Jython.org site do not have search >facilities (AFAICT) and I was unable to find anything about >it in my mail application (back to 7/21/2001), so I apologize ahead >of time if it has. > >Sincerely, >Anthony Eden > > >_______________________________________________ >Jython-users mailing list >Jyt...@li... >https://lists.sourceforge.net/lists/listinfo/jython-users -- Brad Cox, PhD; bc...@vi... 703 361 4751 o For industrial age goods there were checks and credit cards. For everything else there is http://virtualschool.edu/mybank o Java Interactive Learning Environment http://virtualschool.edu/jile o Java Web Application Architecture: http://virtualschool.edu/jwaa |
From: Samuele P. <pe...@in...> - 2002-03-26 19:48:49
|
From: Brad Cox <bc...@vi...> > > PPS: Probably harder, supporting expansion of variables within > strings ala' perl would immediately make python a favorite. The > ${variable}s workaround that was offered here earlier is a bit > obscure for heavily used stuff like expanding variable information > into html template files. > Incredible as it may seem <wink>, there have been serious discussions about this on python-dev, and there's even a PEP http://python.sourceforge.net/peps/pep-0215.html But for the moment the discsussions have not converged anywhere, the main problem being how to disentangle the confusion wrt to the old idioms (deprecate them (hard because of legacy), or organzize things in a hierarchy of increasing functionality but how) and the syntax. Don't hold your breath (see http://www.python.org/doc/essays/pepparade.html ), anyway we cannot support this indipendently from Python. regards. |
From: Kevin B. <kb...@ca...> - 2002-03-26 20:22:38
|
Brad Cox wrote: > PS: The token (+ vs , vs nothing) isn't important. What *is* is that > the result winds up as a string, not array, tuple, etc. The string formatting always yields a string. > PPS: Probably harder, supporting expansion of variables within strings > ala' perl would immediately make python a favorite. The ${variable}s > workaround that was offered here earlier is a bit obscure for heavily > used stuff like expanding variable information into html template files. I'm not sure how string formatting is "obscure" - it is described in the python tutorial: http://www.python.org/doc/current/tut/node9.html#SECTION009100000000000000000 and it is heavily used in Python code (cd jython/Lib; grep \% *py if you'd like a lot of examples...). Also, it is likely to be faster than '+' would be... BTW, watch your characters: percent and parens, not dollar and braces > Ideally, this should work for any expression (variables, subroutine > calls, arrays, tuples, etc). Ahh, you want a formatter that evaluates expressions? Not hard to make one. Since named-value % formatting is based on dictionaries, you can replace the dictionary with your own class with a "__getitem__" function. This lets you completely replace the % evaluation with whatever you'd like: --- formatter.py --- import operator class Formatter: def __init__( self, locals=None ): self.locals = locals or globals() def __getitem__( self, name ): return eval( name, self.locals ) asdf=10 template = """asdf=%(asdf)s simple expression=%(20+30)s complex expression=%(reduce(operator.add, range( 10 )))s hairier than you want: %(Template( {"one":1, "two":4, "four":16, "4":16} ).format( "Square of four is %(four)s, but the digit 4 is %(4)s" ))s """ print template % Formatter() ---- output is: >>> ## working on region in file d:/TEMP/python-3181zD... asdf=10 simple expression=50 complex expression=45 hairier than you want: Square of four is 16, but the digit 4 is 4 >>> Gosh, but I love Python. :-) Bonus points if you figure out why the outputs of four & 4 are different. :-) kb |
From: Samuele P. <pe...@in...> - 2002-03-26 22:16:45
|
From: Kevin Butler <kb...@ca...> > > print template % Formatter() > You can use Formatter also in this way: import sys def i(str): uplocals = sys._getframe().f_back.f_locals return str % Formatter(locals = uplocals) print i(template) As taste goes YMMV. regards. |
From: Kevin B. <kb...@ca...> - 2002-03-26 20:53:35
|
I wrote: > hairier than you want: %(Template( {"one":1, "two":4, "four":16, "4":16} > ).format( "Square of four is %(four)s, but the digit 4 is %(4)s" ))s > """ Woops! Just realized I included code using my original Template class name & format method. Gotta remember to run all examples in a new interpreter before posting. :-) This example will work better: import operator class Formatter: def __init__( self, locals=None ): self.locals = locals or globals() def __getitem__( self, name ): return eval( name, self.locals ) asdf=10 template = """asdf=%(asdf)s simple expression=%(20+30)s complex expression=%(reduce(operator.add, range( 10 )))s hairier than you want: %("Square of four is %(four)s, but the digit 4 is %(4)s" % Formatter( {"one":1, "two":4, "four":16, "4":16} ))s """ print template % Formatter() Output: >>> ## working on region in file d:/TEMP/python-318cSW... asdf=10 simple expression=50 complex expression=45 hairier than you want: Square of four is 16, but the digit 4 is 4 >>> (I should also point out that eval may not be blindingly fast, and there are security concerns in evaluating any user-provided expressions...) kb |
From: Brad C. <bc...@vi...> - 2002-03-26 21:18:03
|
Thanks to all who replied. Will see if Kevin's suggestion floats my boat. If not, I'll wheel out the MLS preprocessor again. PS: MLS addresses the syntax issues in Java by using {{diggraphs}} as syntactic sugar for "string". So... print {{ <html><title>{{anyExpressionWhatSoEver}}</title></html> }}; expands into precisely this print "\n"+ <html><title>"+anyExpressionWhatSoEver+"</title></html>\n"+ ""; Even-level nestings (including zeroth) expand into strings while odd-level nestings expand as the original text. A simple solution to a common problem (FAR simpler than JSP or Velocity) that doesn't involve language modifications at all. -- Brad Cox, PhD; bc...@vi... 703 361 4751 o For industrial age goods there were checks and credit cards. For everything else there is http://virtualschool.edu/mybank o Java Interactive Learning Environment http://virtualschool.edu/jile o Java Web Application Architecture: http://virtualschool.edu/jwaa |