Re: Why do Pythoneers reinvent the wheel?
François Pinard wrote: > In computer > science, I often saw old concepts resurrecting with new names, and then > mistaken for recent inventions. New ideas are not so frequent... > "There are very few problems in Computer Science that cannot be solved with an additional level of indirection." -- Dunno who said it first, but I wish it was me. -- http://mail.python.org/mailman/listinfo/python-list
Appending paths relative to the current file to sys.path
Out of interest, are there any standard Python modules that do this: def appendRelativeIncludePath(*relpath): dir = os.path.abspath(os.path.join(os.path.dirname(__file__), *relpath)) if not dir in sys.path: sys.path.append(dir) I ask because I often find myself doing this: # myproject/lib/mymodule/test/test.py if __name__ == '__main__': import os.path import sys dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) if not dir in sys.path: sys.path.append(dir) import mymodule # it's always 2 directories up from here And it seems like a lot to type so often. I can't factor out this functionality unless I create a little module for doing this and install it in a standard include path. You see I dream of doing this: # myproject/lib/mymodule/test/test.py if __name__ == '__main__': import astandardmodule astandardmodule.appendRelativeIncludePath('..', '..') import mymodule Which, as you can see, is much shorter. ;) -- Greg McIntyre -- http://mail.python.org/mailman/listinfo/python-list
libgmail login failure
There doesnt seem to be a reliable support channel for libgmail so i figured this group might have some people who could help. I have the latest version(from cvs) of libgmail.py, lgconstants.py and mkconstants.py with python version 2.3.3. gmailfs fails with a login error. I also tried a test login script and it fails on logon also. I double-checked my username/passwords as well trying to actually login from the web and with two different accounts. They both work but both fail with libgmail login attempts. I am not behind any type of proxy or strange http firewall that I know of(wget works fine w/o tweaking). Here is the error from gmailfs. The last couple lines are identical if I try the test login script: --- [EMAIL PROTECTED] root]# mount -t gmailfs /usr/local/bin/gmailfs.py /gmailtest -o [EMAIL PROTECTED],password=,fsname=tE sT1nG [EMAIL PROTECTED] root]# gmailfs.py:Gmailfs:mountpoint: '/gmailtest' gmailfs.py:Gmailfs:unnamed mount options: ['rw'] gmailfs.py:Gmailfs:named mount options: {'username': '[EMAIL PROTECTED]', 'password': '', 'fsna me': 'tEsT1nG'} Traceback (most recent call last): File "/usr/local/bin/gmailfs.py", line 1117, in ? server = Gmailfs() File "/usr/local/bin/gmailfs.py", line 603, in __init__ self.ga.login() File "/usr/lib/python2.3/site-packages/libgmail.py", line 300, in login raise GmailLoginFailure("Login failed. (Wrong username/password?)") libgmail.GmailLoginFailure: 'Login failed. (Wrong username/password?)' -- http://mail.python.org/mailman/listinfo/python-list
Re: python callbacks and windows
[EMAIL PROTECTED] wrote: > I was wondering if anyone could point me to an example. Currently i > have a c++ program which calls and c++ dll (i created both). The dll > uses SendMessage to pass messages back to the calling .exe, and the > .exe process the messages in it's Windows Procedure function > WindProc(). > > What i want is to receive these messages ( the contents of each message > will be plain text), in python using a callback (i think this is what i > need). > > I don't know whether (or if it's possible) to implement the windows > procedure and stuff in python, eliminating the need for the .exe > altogether. > > or should i do it the other way, to add a callback function in python, > and for the windows procedure in the .exe to call this python callback? > > in any case, some simple code examples would be great. > > cheers. What you ask for is somewhat hard to find easy answers for. But here is something that might help: 1. Example of Python function to a C library as a callback: http://groups.google.com/group/comp.lang.python/browse_thread/thread/cd4a6aa29e75e72d/6c8eeeffba9fa14b?lnk=st&q=%22Python+function+to+a+C+library+as+a+callback%22&rnum=1&hl=en#6c8eeeffba9fa14b 2. Venster, a highly native Windows GUI toolkit for Python based on the ctypes ffi library: http://venster.sourceforge.net/htdocs/index.html Khalid -- http://mail.python.org/mailman/listinfo/python-list
Re: issue with string.Template
Michele Simionato wrote: > This is somewhat in between a bug report and a feature request. > I was using the new string.Template class and I have run into a > few issues that I traced back to the usage of the idiom > > '%s' % val > > in the 'convert' helper function in Template.substitute. > > I do not understand why '%s' % val was used instead of just > str(val). The reason is written in the code comments: """ # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. """ > P.S. at the end, the problem is that string interpolation with > positional arguments is somewhat of a hack, but fixing this will > have to wait until Python 3000 ... The plan for Py3.0 is to have a formatting function that doesn't have the same tuple vs scalar issue. > So, take this as a bug report if the behavior is not intended and > as a feature request if the current behaviour is the intended > one ;) Feel free to post a SF report. If Barry wants to alter the behavior, it is easy enough to do: try: return str(s) except UnicodeEncodeError: return unicode(s) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: List of integers & L.I.S. (SPOILER)
[Tim Peters, on the problem at http://spoj.sphere.pl/problems/SUPPER/ ] >> Oh, it's not that bad . I took a stab at a Python program for >> this, and it passed (3.44 seconds). >> ... >> I didn't make any effort to speed this, beyond picking a reasonable >> algorithm, so maybe someone else can slash the runtime [Bryan Olson] > Hmmm ... I used the Theta(n lg n) algorithm ... how the heck... > Aha! The 'bisect' module changed since last I looked. It still > has the Python implementation, but then the last few lines say: > > # Overwrite above definitions with a fast C implementation > try: > from _bisect import bisect_right, bisect_left, insort_left, > insort_right, insort, bisect > except ImportError: > pass > > Binary-search is the inner-loop in this algorithm. I wrote my > own binary-search, so I was executing Theta(n lg n) Python > statements. Tim's use of bisect means that his inner-loop is > in C, so he does Theta(n) Python statements and Theta(n lg n) C > statement. That's part of it, but doesn't account for enough. If I disable the C implementation of bisect (replace the "from ..." import above with a "pass"), the program takes about 50% longer, which would still leave it well under the 9-second SPOJ time limit. That's without psyco. With psyco, it takes about the same time with the Python implementation of bisect as with the C implementation. Proably more important was my findall() routine. It does redundant work, and its runtime seems hard to analyze, but it's conceptually simple and actual timing showed it takes about a third of the time consumed by my crack() on random 100,000-element permutations. In fact, findall() takes very close to the amount of time needed just to read a giant line of input and convert it to a list of ints (without psyco; with psyco converting the input takes longer than findall()). Possible surprise: there's a simple trick that allows rewriting findall() to produce the result list in sorted order directly, instead of building it in "random" order and sorting it at the end. That made no measurable difference. > The key to fast Python: use a good algorithm, Absolutely! > and keep the inner loop in C. Usually ;-) Add another: especially for long-term maintenance, readability, stability and performance, use a library function instead of rolling your own. The chance that Raymond Hettinger is going to recode _your_ functions in C is approximately 0 ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: List of integers & L.I.S. (SPOILER)
Tim Peters wrote: > [Bryan Olson, on the problem at > http://spoj.sphere.pl/problems/SUPPER/ > ] > >>I never intended to submit this program for competition. The >>contest ranks in speed order, and there is no way Python can >>compete with truly-compiled languages on such low-level code. >>I'd bet money that the algorithm I used (coded in C) can run >>with the winners. I also think I'd wager that the Python version >>outright trumps them on code size. > > Oh, it's not that bad . I took a stab at a Python program for > this, and it passed (3.44 seconds). [...] > I didn't make any effort to speed this, beyond picking a reasonable > algorithm, so maybe someone else can slash the runtime Hmmm ... I used the Theta(n lg n) algorithm ... how the heck... Aha! The 'bisect' module changed since last I looked. It still has the Python implementation, but then the last few lines say: # Overwrite above definitions with a fast C implementation try: from _bisect import bisect_right, bisect_left, insort_left, insort_right, insort, bisect except ImportError: pass Binary-search is the inner-loop in this algorithm. I wrote my own binary-search, so I was executing Theta(n lg n) Python statements. Tim's use of bisect means that his inner-loop is in C, so he does Theta(n) Python statements and Theta(n lg n) C statement. The key to fast Python: use a good algorithm, and keep the inner loop in C. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: pinging from within python
Impacket module can helps you to construct the ip/icmp packet structure, then you can send the packet and wait for the ECHOREPLY by using a RAW_SOCKET. Here's an example: http://oss.coresecurity.com/impacket/ping.py Cheers > I need a simple script to run the ping command with some parameters and be > able to read the return value of the ping function. Any pointers will be > appreciated > > thanks > m.smadi -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Carl Friedrich Bolz wrote: > a) building LLVM is not _that_ bad (you don't need to build the > C-frontend, which is the really messy part) That piece of wisdom must have passed me by last time, when I probably heeded the scary warning from the configure script and made the mistake of getting the C front end. This time, the build process was virtually effortless, and I'll now have to investigate LLVM further. Thanks for the tip! Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: python callbacks and windows
On 9 Sep 2005 03:20:09 -0700, [EMAIL PROTECTED] wrote: >I was wondering if anyone could point me to an example. Currently i >have a c++ program which calls and c++ dll (i created both). The dll >uses SendMessage to pass messages back to the calling .exe, and the >.exe process the messages in it's Windows Procedure function >WindProc(). > This sounds like your main program is ordinary C++ GUI and the dll could be anything, but you probably cause it to be loaded and initialized at least from the GUI main prog, maybe just by automatic dependency loading. It is not clear whether you have a lot of code and would like to use python for some aspect of processing special messages, or whether you have a tentative start in C++ for an application you'd rather develop entirely in python. What you want to do next will probably depend on what you have. >What i want is to receive these messages ( the contents of each message >will be plain text), in python using a callback (i think this is what i >need). I would guess that if you want to use windows messages, it might be easiest to receive them in the main message loop and to recognize the special messages there (vs all the standard windows stuff) and at that point call from C++ to python to process the plain text contents. The question is what do you want to get back, and what side effects and state-ful processing might you want to do, and if there is state, do you want to maintain it in python or C++, and how to you want to access from the other side if you need to. Calling from C++ to python and vice versa is discussed in the docs re extensions and embedding etc. (See http://python.org/doc/ links to "Extending and Embedding" and "Python/C API") > >I don't know whether (or if it's possible) to implement the windows >procedure and stuff in python, eliminating the need for the .exe >altogether. Have you looked at tkinter? It will let you make a GUI that runs under windows, and then you can code in python. > >or should i do it the other way, to add a callback function in python, >and for the windows procedure in the .exe to call this python callback? > >in any case, some simple code examples would be great. > I would suggest downloading the python sources zip or tgz in addition to the standard installation (which presumably you already have). The reason is that the sources contain a demo subdirectory with useful examples of what can be done with tkinter (and other stuff as well). Some of it could stand to be updated to take advantage of current python, but you can run the demo examples and modify them to learn a lot about what can be done. BTW, does python.org have a directory tree somewhere with a duplicate of a source installation that people could browse with ftp:// ? That way, people could get access to the demos and other sources without having to download the whole thing, (e.g., ftp://python.org/pub/python/2.4.1/Python-2.4.1.tgz is ~9mb) and people could also post with url references to particular sources. Seems like providing source trees could be automated, so there would only be an initial effort involved. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: make sure entire string was parsed
Steve - >>I have to differentiate between: >> (NP -x-y) >>and: >> (NP-x -y) >>I'm doing this now using Combine. Does that seem right? If your word char set is just alphanums+"-", then this will work without doing anything unnatural with leaveWhitespace: from pyparsing import * thing = Word(alphanums+"-") LPAREN = Literal("(").suppress() RPAREN = Literal(")").suppress() node = LPAREN + OneOrMore(thing) + RPAREN print node.parseString("(NP -x-y)") print node.parseString("(NP-x -y)") will print: ['NP', '-x-y'] ['NP-x', '-y'] Your examples helped me to see what my operator precedence concern was. Fortunately, your usage was an And, composed using '+' operators. If your construct was a MatchFirst, composed using '|' operators, things aren't so pretty: print 2 << 1 | 3 print 2 << (1 | 3) 7 16 So I've just gotten into the habit of parenthesizing anything I load into a Forward using '<<'. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How to upgrade to 2.4.1 on Mac OS X tiger
Mike Meyer wrote: > Depends on what you want to do with it. If you favor one of the > package systems (fink, darwinports, emerge), you probably want to use > that one. That way, you won't have to worry about whether or not > another package from that system will find the one Python you > installed (and hence all the things installed by it), or will install > things again. > > Otherwise, I agree with Robert - use the official one. Of course, if > one of the other two includes all the extra functionality you want, > use it. One thing that should be noted is that fink's python, last time I checked, isn't built as a framework build, so it can't talk to the native GUI or use PyObjC. That's a shame. darwinports' python is a framework build, but does silly things like linking to an X11 version of Tk instead of TclTkAqua like the official distribution. ActiveState's python is also a framework build, but I don't see how it adds anything beyond what's provided by the official installer besides packaging freely available documentation. I have no idea how emerge's python is built. The official build is going to be the most widely used and tested. Tools like py2app and PyObjC are guaranteed to work with it. > Come to think of it, what's installed by Apple may count as a > different distribution as well. It certainly includes more than just > the official distribution. It's also old and probably won't be the same version in 10.5. If you want any control over how you distribute your apps, use the official 2.4.1 binary and embed the interpreter inside your .app bundle with py2app. -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Fun with decorators and unification dispatch
Well, the Matrix matching function now works as described above: @Arity( MatchMatrix( MatchInteger.n, MatchInteger.n ).x ) Now I am trying to see if I can write the rules for Derviative()... -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Paul Boddie wrote: > Michael Sparks wrote: >> Well, you did say you want help with locating problems. One problem with >> this is it doesn't build... > > I found that I needed both the libgc and libgc-dev packages for my > Kubuntu distribution - installing them fixed the include issues that > you observed - and it does appear to be the Boehm-Demers-Weiser GC > library, yes. The only other issue I observed was the importing of the > profile and pstats modules which don't exist on my system, but those > imports seemed to be redundant and could be commented out anyway. Mark's also let me know this. Part of the problem is the version in SuSE 9.3 of the GC used is ancient - it should be version 6.5 onwards. Also for people compiling from source you (at minimum) should be using the configure line along the lines of: ./configure --enable-cplusplus If you don't, you get build problems because one of the needed libraries isn't built by default. I started off with the obvious "hello world" type program : print "GAME OVER" Which compiled cleanly and worked as expected. I then read Mark's short paper linked from his blog "Efficient Implementation of Modern Imperative Languages; Application to Python", and got concerned by the comments: """We have decided not to investigate two types of features: [...snip...]; and those features that may be turned off without affecting correct programs, e.g. array bounds checking, and exceptions""" That set some alarm bells ringing, largely because LBYL being deprecated by many people in favour of exceptions based code. (And more to the point, widely used as a result) As a result, I tried a trivial, but obvious program that should have clear behaviour: x = [] print "GAME OVER" x.append(5) print x[0] try: print x[1] print "This should never be seen..." except IndexError: print "It's OK, we caught it..." This compiles, but unfortunately has the following behaviour: GAME OVER 5 0 This should never be seen... It's OK, we caught it... Obviously, neither the 0 nor the message following should have been displayed. It's a pity that this assumption was made, but given the short time the project's been going I can understand it, hopefully Mark will continue towards greater python compliance :) Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to upgrade to 2.4.1 on Mac OS X tiger
"Mike P." <[EMAIL PROTECTED]> writes: > I just got a Mac and was wondering the same thing as the original poster - > how to move to 2.4, but I found out there was more than one version. > So in addition to the Apple installation of 2.3, there are 4 versions of > Python 2.4 (ActivePython, MacPython, fink, darwinports). emerge probably has one as well. And Robert Kern mentioned the official one. The package systems may use one of the others, especially if they are available in source form. If they all do, there are only three distributions (ActivePython, MacPython, and the official one), with the packages installing them in different places. > Which one should I go for? What are other people using (i.e. which is the > most popular version)? Any particular advantages/disadvantages for each > version? Depends on what you want to do with it. If you favor one of the package systems (fink, darwinports, emerge), you probably want to use that one. That way, you won't have to worry about whether or not another package from that system will find the one Python you installed (and hence all the things installed by it), or will install things again. Otherwise, I agree with Robert - use the official one. Of course, if one of the other two includes all the extra functionality you want, use it. Come to think of it, what's installed by Apple may count as a different distribution as well. It certainly includes more than just the official distribution. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Hi Mark! Mark Dufour wrote: >>>After nine months of hard work, I am proud to introduce my baby to the >>>world: an experimental Python-to-C++ compiler. >>Wow, looks really cool. But why that instead of Pypy? > > I agree with anyone that a JIT compiler that supports the full Python > semantics (which I thought to be the goal of PyPy?) is probably the > best long term solution. It will really be a lot of work, however, and > in general probably result in slower code than what my compiler > produces, when it works (because of run-time overheads, lack of global > optimizations.) Although it is one of the goals of the PyPy project is producing a JIT for Python at some point in the future, it also contains a _static_ Python compiler right now: The whole source code of PyPy's interpreter is written in RPython, a restricted subset of the Python language. This subset is choosen in a way to make type inference possible and translate the code to a more low level language (at the moment C and LLVM are supported). This part of PyPy, the translator (http://codespeak.net/pypy/dist/pypy/doc/translation.html) has quite some similarities to Shed Skin. The kind of code that Shed Skin supports and RPython look quite similar (the biggest difference I see right now is that RPython supports exceptions). This was probably what Paul was referring to. The translator is needed to translate the whole PyPy interpreter into a low level language to get speed back, so Shed Skin and the translator exist for the same reason. > Considering that Shed Skin does what it does in only about 7500 lines > (5500 without C++ implementations of builtins), and is extreme in both > the requirements it puts on the compiler and in the speed of the > resulting code, for me personally it is just a very appealing > alternative to investigate (I like extremes :-)) It should work for > many programs of the type I usually write (algorithms, compilers..), > so it's also a case of scratching my own itch. Shed Skin looks indeed quite impressive. If you are interested in discussing static translation of subsets of Python a bit or are even interested in getting to know PyPy a bit better feel free to contact us (http://codespeak.net/pypy/dist/pypy/doc/contact.html). Cheers, Carl Friedrich Bolz -- http://mail.python.org/mailman/listinfo/python-list
packaging python for install.
Hi everyone, I have created an App that embedds the python interpreter and I am now in the process of creating an installer. I am currently linking python24.lib, but it is only 184k and I suspect that it imports other dlls... I am also using numarray. Does anyone have any experiences in packaging python with an application in a single installer ? Has that been done before ? Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: calling command line programs?
Grant Edwards wrote: > On 2005-09-10, chriss <[EMAIL PROTECTED]> wrote: > >>> Take a look at os.popen, os.spawn, or the popen2, and >>> subprocess modules. >>> >>> That last one seems to be gaining popularity. >> >> The suggested modules and functions have been deprecated according to the >> python 2.4 docs. The doc suggests to use the functions in the >> 'subprocess' module. > > The subprocess module is depricated? > no, the subrocess module intends to replace modules and functions such as: os.system os.spawn* os.popen* popen2.* commands.* have a look at http://python.org/doc/2.4.1/lib/module-subprocess.html -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode, C++, python 2.2
Trond Eivind Glomsrød wrote: > I am currently writing a python interface to a C++ library. Some of the > functions in this library take unicode strings (UTF-8, mostly) as > arguments. > > However, when getting these data I run into problem on python 2.2 > (RHEL3) - while the data is all nice UCS4 in 2.3, in 2.2 it seems to be > UTF-8 on top of UCS4. UTF8 encoded in UCS4, meaning that 3 bytes of the > UCS4 char is 0 and the first one contains a byte of the string encoding > in UTF-8. > > Is there a trick to get python 2.2 to do UCS4 more cleanly? It's hard to tell from your message what your problem really is, as we have not clue what "these data" are. How do you know they are "nice UCS4" in 2.3? Are you looking at the internal representation at the C level, or are you looking at something else? Do you use byte strings or Unicode strings? You tried to explain what "UTF8 encoded in UCS4" might be, but I'm not sure I understand the explanation: what precise sequence of statements did you use to create such a thing, and what precisely does it look like (what exact byte is first, what is second, and so on)? Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Mark Dufour wrote: > After nine months of hard work, I am proud to introduce my baby to the > world: an experimental Python-to-C++ compiler. Good work. I have good news and bad news. First the good news: ShedSkin (SS) more or less works on Windows. After patching gc6.5 for MinGW, building it, and testing it on WinXP with some succuess, and after patching my local copy of SS, I can get the test.py to compile from Python to C++, and it seems that I can get almost all the unit tests in unit.py to pass. Here is what I used: 1. shedskin-0.0.1 2. pyMinGW patched and MinGW compiled Python 2.4.1 from CVS: Python 2.4.1+ (#65, Aug 31 2005, 22:34:14) [GCC 3.4.4 (mingw special)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 3. MinGW 3.4.4: g++ -v Reading specs from e:/UTILIT~1/PROGRA~1/MINGW/BIN/../lib/gcc/mingw32/3.4.4/specs Configured with: ../gcc/configure --with-gcc --with-gnu-ld --with-gnu-as --host=mingw32 --target=mingw32 --prefix=/mingw --enable-threads --disable-nls --enable-languages=c,c++,f77,ada,objc,java --disable-win32-registry --disable-shared --enable-sjlj-exceptions --enable-libgcj --disable-java-awt --without-x --enable-java-gc=boehm --disable-libgcj-debug --enable-interpreter --enable-hash-synchronization --enable-libstdcxx-debug Thread model: win32 gcc version 3.4.4 (mingw special) 4. Also using: - mingw-runtime 3.8 - w32api-3.3 - binutils-2.16.91-20050827-1 - gc6.5 (Bohem GC) locally patched Now the bad news. Four tests in Unit.py fail, brief output is as follows[1]. [SKIP 19532 lines] *** tests failed: 4 [(60, '__class__ and __name__ attributes'), (85, 'ifa: mixing strings and lists of strings in the same list'), (122, 'neural network simulator XXX later: recursive customization, plus some small fixes'), (124, 'small factorization program by Rohit Krishna Kumar')] Moreover, and since the GC system you used only works in "recent versions of Windows", it follows that this solution will not work in all versions. I tested it on Win98 and both GC tests and SS's unit.py tests crash; although SS can still seem to compile the tests to C++. At any rate, if anyone is interested in the patches they can be downloaded from [2]. Regards, Khalid [1] The entire output of unit.py can also be found at [2] [2] http://jove.prohosting.com/iwave/ipython/Patches.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Predicting Thumbnail Sizes from PIL
Fredrik Lundh wrote: [snip..] > > the algorithm is: > > x, y = im.size > if x > size[0]: y = max(y * size[0] / x, 1); x = size[0] > if y > size[1]: x = max(x * size[1] / y, 1); y = size[1] > size = x, y > > that is, it shrinks the image horizontally first, and it then shrinks the > resulting image vertically: > > >>> 816 * 697 / 800 > 710 > >>> 697 * 697 / 710 > 684 > Thanks ! This was also helpful to me. Fuzzyman http://www.voidspace.org.uk/python > -- http://mail.python.org/mailman/listinfo/python-list
ANNOUNCE: SMC - State Machine Compiler v. 4.2.0
SMC - The State Machine Compiler v. 4.2.0 Requires: Java 1.4.1 SE (Standard Edition) or better. Download: http://sourceforge.net/projects/smc Home Page: http://smc.sourceforge.net = What's New? = + Added C, Perl and Ruby language generation. + Added method valueOf(int stateId) to Java, C# and VB.Net to allow developers to hand-serialize and deserialize state machines. = Bug fixes = + (C#) Removed extraneous "bool loopbackFlag = false" line from Default state transitions. + (C#) Added "Trace.Listeners.Add(myWriter)" line when generating debug code. By not having this line it prevented debug output from being outuput. + Corrected parser abend when a transition was missing an endstate. = What is SMC? = SMC takes a state machine description (stored in a .sm file) and generates State pattern classes in a target language (C++, Java, Tcl, VB.Net, C# and Python are currently supported). SMC is a console-based app written in Java which means SMC can run anywhere Java (1.4.1 or better) can run. The download package includes an example directory showing how SMC can used with C++, Java, Tcl (requires [incr Tcl] package), VB.Net, C# and Python. The examples range from trivial to GUI apps. = How can I learn more? = At http://smc.sourceforge.net. You can access the SMC Programmer's Manual there as well. While you're there, check out the SMC demo applet at http://smc.sourceforge.net/SmcDemo.htm. = Where can I get it? = SMC and the Programmer's Manual can be downloaded from http://sourceforge.net/projects/smc. You can also use this website to: + Ask questions (via the Public Forum's Help discussion) + Submit a bug. + Join a mailing list. + Access SMC documentation. + Access SMC's source code in the CVS repository. (Note: in order to make full use of SourceForge capabilities, you must be a SourceForge member. If you are not a member, head over to http://sourceforge.net/account/register.php and sign up. SourceForge membership is free - no money, no requirements and NO SPAM! Membership has its benefits.) If you have any problems, surf over to http://sourceforge.net/forum/forum.php?forum_id=27865 and report the problem. I will try and answer you via the Help forum as quickly as I can. Enjoy! Charles Rapp -- http://mail.python.org/mailman/listinfo/python-list
CGIHTTPServer, popen3, and windoze
Hello all, I may well post this a a bug on Monday (after testing with Python 2.3) - but I thought I'd post here to see if anyone has any ideas. The basic problem is that under Python 2.4 (and windoze XP SP2) CGIHTTPServer isn't passing the CGI environment variables to scripts it runs. I've checked that the environment variables all exist in os.environ before the subprocess is launched using popen3. I've *also* checked that when I launch a test subprocess using popen3 myself, environment variables *are* passed on - so I'm a bit confused... I wonder if anyone can shed any light on this behavior ? All the best, Fuzzyman http://www.voidspace.org.uk/python P.S. I've also patched CGIHTTPServer so that it can handle paths wih spaces and CGIs in subdirectories of the 'cgi-bin' folder. I'll *suggest* these changes to the maintainers - but my tests were on the original version. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about consistency in python language
"Robert Kern" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > In many, many fonts 'l' and '1' look close enough to be easily mistaken > for one another In the default font used by Outlook Express, displayed on my 1078x786 screen, the only difference I can see, using a magnifying glass on side-by-side characters (l1 = el-onel), is that 'el' is one pixel taller than the 'one'. The serifs appear the same, down to the anti-alias gray pixels. (To my surprise, this makes 'lbdk' a pixel taller than uppercase chars!) Now I know ;-). But 1 isolated from l is still difficult to distinguish. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python versus Perl
"Michael Sparks" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > That said, if you do describe it that way, it'd be more accurate to > describe > the python binary as a compiler/runtime rather than interpreter since > it'd > be more accurate. If Java calls its runtime bytecode interpreter a 'runtime' rather than 'interpreter', so can we. Ditto, if applicable, to .NET clr. Still more accurate, I think, is 'intergrated compiler and runtime'. > It strikes me as ironic that python would probably gain more credibility > with some circles if it had two binaries like this, even though it'd be a > step backwards from a usability perspective :-) Yes. The integration is a practical necessity for interactive mode with alternative compile and execute. For batch mode, integration consists of the very nice built-in mini-make. > Personally I agree that any language that is described as interpreted has > an > image issue. However I'm not sure who's problem that is - some people > claim > it's "Python's problem", however personally I'd view as a problem for the > people who buy into "interpretted bad, compiled good" argument. After > all, > they're the ones limiting themselves, and missing out on a whole class of > languages (of which python is just one of course) ! That has been my response. And as a Python programmer, that is the end of it. But as a responder/advocate, I am beginning to accept that the misperception is wide enough to also be a bit my problem. Hence my small effort for a more effective vocabulary. Thanks for your contribution. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Michael Sparks wrote: > Well, you did say you want help with locating problems. One problem with > this is it doesn't build... I found that I needed both the libgc and libgc-dev packages for my Kubuntu distribution - installing them fixed the include issues that you observed - and it does appear to be the Boehm-Demers-Weiser GC library, yes. The only other issue I observed was the importing of the profile and pstats modules which don't exist on my system, but those imports seemed to be redundant and could be commented out anyway. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: pinging from within python
On 2005-09-11, M.N.A.Smadi <[EMAIL PROTECTED]> wrote: > I need a simple script to run the ping command with some parameters and > be able to read the return value of the ping function. Any pointers will > be appreciated http://www.google.com/search?hl=en&q=python+ping -- Grant Edwards grante Yow! I think my CAREER at is RUINED!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
pinging from within python
hi; I need a simple script to run the ping command with some parameters and be able to read the return value of the ping function. Any pointers will be appreciated thanks m.smadi -- http://mail.python.org/mailman/listinfo/python-list
Re: make sure entire string was parsed
Paul McGuire wrote: > Thanks for giving pyparsing a try! To see whether your input text > consumes the whole string, add a StringEnd() element to the end of your > BNF. Then if there is more text after the parsed text, parseString > will throw a ParseException. Thanks, that's exactly what I was looking for. > I notice you call leaveWhitespace on several of your parse elements, so > you may have to rstrip() the input text before calling parseString. I > am curious whether leaveWhitespace is really necessary for your > grammar. If it is, you can usually just call leaveWhitespace on the > root element, and this will propagate to all the sub elements. Yeah, sorry, I was still messing around with that part of the code. My problem is that I have to differentiate between: (NP -x-y) and: (NP-x -y) I'm doing this now using Combine. Does that seem right? > Lastly, you may get caught up with operator precedence, I think your > node assignment statement may need to change from > node << start + (branch_node | leaf_node) + end > to > node << (start + (branch_node | leaf_node) + end) I think I'm okay: py> 2 << 1 + 2 16 py> (2 << 1) + 2 6 py> 2 << (1 + 2) 16 Thanks for the help! STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Hi Paul! Paul Boddie wrote: > Carl Friedrich Bolz wrote: >>>. there is no reason why the pypy project can't have a .NET architecture >>>instead of the java-like arrangement I assume it has now >>Sorry, I can't really follow you here. In what way does PyPy have a >>Java-like arrangement? > > I imagine that this remark was made in reference to the just-in-time > compilation techniques that PyPy may end up using, although I was under > the impression that most CLR implementations also use such techniques > (and it is possible to compile Java to native code as gcj proves). Well, PyPy is still quite far from having a JIT build in. Plus the JIT-techniques will probably differ quite a bit from Java _and_ the CLR :-). > But on the subject of LLVM: although it seems like a very interesting > and versatile piece of software, it also seems to be fairly difficult > to build; my last attempt made the old-style gcc bootstrapping process > seem like double-clicking on setup.exe. Does this not worry the PyPy > team, or did I overlook some easier approach? (Noting that a Debian > package exists for LLVM 1.4 but not 1.5.) We are not that worried about this since a) building LLVM is not _that_ bad (you don't need to build the C-frontend, which is the really messy part) and b) the LLVM-backend is one of the more experimental backends we have anyway (in fact, we have discovered some bugs in LLVM with PyPy already). Since the C backend is quite stable we are not dependent solely on LLVM so this is not too big a problem. Note that this doesn't mean that the LLVM backend is not important: it's the only other backend (apart from the C one) that can succesfully translate the whole PyPy interpreter. Cheers, Carl Friedrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Python versus Perl
Terry Reedy wrote: [...] > I am being picky because various people have claimed that Python suffers > in popularity because it is known as an 'interpreted language'. So maybe > advocates should be more careful than we have been to not reinforce the > misunderstanding. I sometimes wonder if it might help people understand the situation if people described as "interpreted in the same way Java is" (However I think that risks confusing things since python doesn't generally come with a JIT subsystem, yet). That said, if you do describe it that way, it'd be more accurate to describe the python binary as a compiler/runtime rather than interpreter since it'd be more accurate. After all: $ python somefile.py Is very close to being the same as: $ javac somefile.java $ java somefile.class It strikes me as ironic that python would probably gain more credibility with some circles if it had two binaries like this, even though it'd be a step backwards from a usability perspective :-) Personally I agree that any language that is described as interpreted has an image issue. However I'm not sure who's problem that is - some people claim it's "Python's problem", however personally I'd view as a problem for the people who buy into "interpretted bad, compiled good" argument. After all, they're the ones limiting themselves, and missing out on a whole class of languages (of which python is just one of course) ! Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Mark Dufour wrote: > With this initial release, I hope to attract other people to help me > locate remaining problems, Well, you did say you want help with locating problems. One problem with this is it doesn't build... If I try and build (following your instructions), I get presented with a whole slew of build errors - knock on errors from the first few: In file included from builtin_.cpp:1: builtin_.hpp:4:29: gc/gc_allocator.h: No such file or directory builtin_.hpp:5:23: gc/gc_cpp.h: No such file or directory In file included from builtin_.cpp:1: builtin_.hpp:89: error: syntax error before `{' token builtin_.hpp:93: error: virtual outside class declaration Which C++ libraries are you dependent on? (Stating this would be really useful, along with specific versions and if possible where you got them :) For reference, I'm building this on SuSE 9.3, under which I also have boehm-gc-3.3.5-5 installed. I suspect you're using the same gc library (having downloaded libgc from sourceforge and finding the includes don't match the above include names) but a different version. For reference this version/distribution of boehm-gc has the following file structure: /usr/include/gc.h /usr/include/gc_backptr.h /usr/include/gc_config_macros.h /usr/include/gc_cpp.h /usr/include/gc_local_alloc.h /usr/include/gc_pthread_redirects.h /usr/lib/libgc.a /usr/lib/libgc.la /usr/lib/libgc.so /usr/lib/libgc.so.1 /usr/lib/libgc.so.1.0.1 It's specifically the gc_cpp.h file that makes me suspect it's the same gc. Regards, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: List of integers & L.I.S. (SPOILER)
[Tim Peters, on the problem at http://spoj.sphere.pl/problems/SUPPER/ ] >> ... [EMAIL PROTECTED] > INCREDIBLE~ > 241433 2005-09-11 04:23:40 Tim Peters accepted 3.44 7096 PYTH > BRAVO! It's different now ;-) I added the two lines import psyco psyco.full() and time dropped to 2.29, while memory consumption zoomed: 2005-09-11 18:44:57 Tim Peters accepted 2.29 42512 PYTH That surprised me: my own test cases on Windows using Python 2.4.1 enjoyed the same order of speedup, but barely increased RAM usage. Perhaps they installed an older (or newer <0.9 wink>) version of psyco. > I just wonder have I grey cells enough for to understand how your > algo works... You do! Work out some small examples by hand, and it will become clear; be sure to read the comments before the code, because they explain it. > and hopefully it's not your last solved problem on the contester. I have to stop now, else I wouldn't do anything else <0.3 wink>. > ... -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Carl Friedrich Bolz wrote: > > > . there is no reason why the pypy project can't have a .NET architecture > > instead of the java-like arrangement I assume it has now > > Sorry, I can't really follow you here. In what way does PyPy have a > Java-like arrangement? I imagine that this remark was made in reference to the just-in-time compilation techniques that PyPy may end up using, although I was under the impression that most CLR implementations also use such techniques (and it is possible to compile Java to native code as gcj proves). But on the subject of LLVM: although it seems like a very interesting and versatile piece of software, it also seems to be fairly difficult to build; my last attempt made the old-style gcc bootstrapping process seem like double-clicking on setup.exe. Does this not worry the PyPy team, or did I overlook some easier approach? (Noting that a Debian package exists for LLVM 1.4 but not 1.5.) Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Why do Pythoneers reinvent the wheel?
Stefano Masini a écrit : (snip) > If such a "quick and dirty" section existed, I think it would also > become a natural randevouz point for innovators. s/randevouz/rendez-vous/ !-) pardon-my-french-ly y'rs -- http://mail.python.org/mailman/listinfo/python-list
Creating BibTex files with XdkBibTeX
I'm looking for a module that is able to create valid BibTex documents. I'm currently using string substitution to create the content, but it is not validated in any way. The only BibTex creation module available in Python (that I can find) is XdkBibTeX (http://artis.imag.fr/Membres/Xavier.Decoret/resources/xdkbibtex/). It is a python wrapper around a C library. Has anyone used this? More interestingly to me... has anyone successfully installed it on Mac OS X? Also, can anyone suggest an alternative? Cheers, Rob Cowie -- http://mail.python.org/mailman/listinfo/python-list
First release of Shed Skin, a Python-to-C++ compiler.
>> After nine months of hard work, I am proud to introduce my baby to the >> world: an experimental Python-to-C++ compiler. >Wow, looks really cool. But why that instead of Pypy? I agree with anyone that a JIT compiler that supports the full Python semantics (which I thought to be the goal of PyPy?) is probably the best long term solution. It will really be a lot of work, however, and in general probably result in slower code than what my compiler produces, when it works (because of run-time overheads, lack of global optimizations.) Considering that Shed Skin does what it does in only about 7500 lines (5500 without C++ implementations of builtins), and is extreme in both the requirements it puts on the compiler and in the speed of the resulting code, for me personally it is just a very appealing alternative to investigate (I like extremes :-)) It should work for many programs of the type I usually write (algorithms, compilers..), so it's also a case of scratching my own itch. thanks! mark. -- http://mail.python.org/mailman/listinfo/python-list
Re: encryption with python
Kirk Job Sluder wrote: > Ron Adam <[EMAIL PROTECTED]> writes: >>I would think that any n digit random number not already in the data >>base would work for an id along with a randomly generated password >>that the student can change if they want. The service provider has >>full access to the data with their own set of id's and passwords, so >>in the case of a lost id, they can just look it up using the customers >>name and/or ssn, or whatever they decide is appropriate. In the case >>of a lost password, they can reset it and get another randomly >>generated password. >> >>Or am I missing something? > > > Not really. My suggestion is that in many cases, if the data is being > used only as a backup password or authentication token, there is no need > for that data to be stored in plaintext. For example, with the > ubiquitous "mother's maiden name" * there is frequently no need to > actually have "Smith," "Jones," or "Gunderson" in the database. > "bf65d781795bb91ee731d25f9a68a5aeb7172bc7" serves the same purpose. For that matter if the encrypted data is used a the key, then there is no need to store the data period. OH... lets see, we'll just store the password, and give them the data instead. Never mind it's a few thousand characters or more. ;-) "Oh, and don't loose your account number BTW." > There are other cases where one-way anonymity is better than a table > linking people to randomly generated userIDs. I'd rather use > cryptographic hashes for research databases than keep a table matching > people to random numbers hanging around. But I'm weird that way. Why would you need a table hanging around? Most databases today are relational, so they are made up of lots of linked tables of records and fields. And each user, can have access to some parts without having access to other parts. So couldn't you create a separate account to access, names and id numbers only? Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: python callbacks and windows
anybody? -- http://mail.python.org/mailman/listinfo/python-list
Re: First release of Shed Skin, a Python-to-C++ compiler.
Hi! adDoc's networker Phil wrote: >> >> experimental Python-to-C++ compiler. >> >> why that instead of Pypy? >> > > . pypy compiles to llvm (low-level virtual machine) bytecode > which is obviously not as fast as the native code coming from c++ compilers; PyPy can currently compile Python code to C code and to LLVM bytecode. Note that even for LLVM bytecode the argument is void since LLVM (despite its name, which might lead one to think that it is Java-like) compiles its bytecode to native assembler. > but the primary mission of pypy > is just having a python system that is > written in something like python rather than c or c++ it's really just plain python (it completely runs on top of CPython after all) together with some restrictions -- which seem similar to the restictions that shedskin imposes btw. > . there is no reason why the pypy project can't have a .NET architecture > instead of the java-like arrangement I assume it has now Sorry, I can't really follow you here. In what way does PyPy have a Java-like arrangement? > . without such a pypy.NET system, > shedskin is offering a service that pypy can't yet provide: > a ( python -> c++ )-conversion allows me to > smoothly integrate python contributions > with my already-staggering c++ library > . I'm not suggesting that pypy should be another > Mono rewritten in python, > because the essential mission of the .NET architecture > is being able to compile > any language of the user`s choice, > to some intermediate language designed to be > far more efficiently compiled to > any machine language of the user`s choice > than any human-readable language such as c++ > . perhaps llvm bytecode can serve as such an intermediate language? > then llvm could be the new c++ (our defacto IL (intermediate language)) > and shedskin (python -> IL=c++) could then be replaced by > the combination of pypy (python -> IL=llvm) > and some incentive for all target platforms > to develope a highly optimized > ( llvm -> native code)-compiler > -- assuming also, that there is available > a highly optimized ( c++ -> llvm bytecode )-compiler . there is. look at the LLVM page for details: www.llvm.org Cheers, Carl Friedrich Bolz -- http://mail.python.org/mailman/listinfo/python-list
ANNOUNCE: twill 0.7.2
ANNOUNCING twill v0.7.2. twill is a simple Web scripting language built on top of Python and John J. Lee's 'mechanize'. It's designed for automated testing of Web sites, but it should prove useful for anybody who needs to interact with Web sites (especially those using logins and cookies) on the command line or via a script. twill is a reimplementation of Cory Dodt's PBP. A twill script looks like this: # go to the /. login page go http://slashdot.org/login.pl # fill in the form fv 1 unickname test fv 1 upasswd test submit # ok, there's no such account ;). show error HTML. show --- This is the third public release of twill, version 0.7.2. (Tagline: "no obvious bugs") I'm still looking for general feedback on usability, as well as suggestions on additional use cases. Download directly here: http://darcs.idyll.org/~t/projects/twill-0.7.2.tar.gz Documentation is online at http://www.idyll.org/~t/www-tools/twill.html --- Miscellaneous details: twill is implemented in Python and uses pyparsing and mechanize. In addition to the existing simple command language, twill can easily be extended with Python. twill also provides a fairly simple and well-documented wrapper around mechanize. twill scripts can be recorded with maxq, although scripts may require some hand tweaking at the moment. See the twill documentation for more information. twill does not understand JavaScript, I'm sorry to say. --- Notable bug fixes and features: * save_html and HTTP debugging commands; * fixed extend_with bugs; * updated pyparsing to 1.3.2; * first PyPi release; -- http://mail.python.org/mailman/listinfo/python-list
Re: Predicting Thumbnail Sizes from PIL
Roger wrote: > I need to calculate the thumbnail sizes PILL will produce from an image. > In most cases I can divide and round by adding .5, but PIL seems to > round differently on odd sized images. > > For example, I want to reduce an 800x816 image to have a maximum size of > 697. (697/816) * 800 = 683.33, so my rounding results in 683. But PIL > produces an image of 684x697. the algorithm is: x, y = im.size if x > size[0]: y = max(y * size[0] / x, 1); x = size[0] if y > size[1]: x = max(x * size[1] / y, 1); y = size[1] size = x, y that is, it shrinks the image horizontally first, and it then shrinks the resulting image vertically: >>> 816 * 697 / 800 710 >>> 697 * 697 / 710 684 -- http://mail.python.org/mailman/listinfo/python-list
Predicting Thumbnail Sizes from PIL
I need to calculate the thumbnail sizes PILL will produce from an image. In most cases I can divide and round by adding .5, but PIL seems to round differently on odd sized images. For example, I want to reduce an 800x816 image to have a maximum size of 697. (697/816) * 800 = 683.33, so my rounding results in 683. But PIL produces an image of 684x697. Is there an easy rule that will always work -- like adding .67 instead of .5? Roger -- http://mail.python.org/mailman/listinfo/python-list
Re: How to upgrade to 2.4.1 on Mac OS X tiger
Mike P. wrote: > Which one should I go for? What are other people using (i.e. which is the > most popular version)? Any particular advantages/disadvantages for each > version? The official one. http://python.org/2.4.1/ -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to upgrade to 2.4.1 on Mac OS X tiger
On Fri, 9 Sep 2005 13:55:03 -0700, Trent Mick wrote: > [Mike Meyer wrote] >> stri ker <[EMAIL PROTECTED]> writes: >>> Has anyone here upgraded from 2.3 to 2.4 on Tiger? >>> If so how'd ya do it? >> >> You don't. You install 2.4 in parallel with 2.3. You can do pretty >> much whatever you want with /usr/bin/python, /usr/local/bin/python, >> etc. - Tiger doesn't seem to use those. I don't remember if I replaced >> one or not, but don't touch anything else about the 2.3 installtion. >> >> I installed the darwinports version of 2.4, and have been using it >> ever since for all my stuff. > > There are also the following install options: > > - ActivePython: > http://www.activestate.com/Products/ActivePython/ > (disclaimer: I make this distro) > > - MacPython: > http://undefined.org/python/#python > by Bob Ippolito > > - fink (similar in spirit to the darwinports project) also has a Python > I believe > > > Trent I just got a Mac and was wondering the same thing as the original poster - how to move to 2.4, but I found out there was more than one version. So in addition to the Apple installation of 2.3, there are 4 versions of Python 2.4 (ActivePython, MacPython, fink, darwinports). Which one should I go for? What are other people using (i.e. which is the most popular version)? Any particular advantages/disadvantages for each version? Cheers. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about consistency in python language
James wrote: [James Stroud wrote:] >>Also, you shouldn't use "1", I mean "l", as a variable name. It gets confusing >>because "l", I mean "1", looks a lot like "1", I mean "l". > > I have seen the same warnning above significantly several times. > Is this problem originally came from the similarities between 'l' and > '1' > or from bad looking news-browser? > Forgive me if it is out of your interests. In many, many fonts 'l' and '1' look close enough to be easily mistaken for one another, especially for people whose vision isn't perfect. The problem exists in the fonts people view and edit code with, not just newsreaders. -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python linear algebra module -- requesting comments on interface
nice interface, but with 3d apps i prefer cgkit's approach, which has vec3, vec4, mat3, mat4 and quat types with lots of useful functions for 3d graphics (like mat4.looakAt(pos, target, up) or mat3.toEulerXYZ()) there are other libs with similar types and functions: cgkit (http://cgkit.sourceforge.net/) pyogre (http://www.ogre3d.org/wiki/index.php/PyOgre) panda3d (http://panda3d.org/) -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about consistency in python language
Steve Holden wrote: > Kay Schluehr wrote: > > Mike Meyer wrote: > > > > > >>Yes, but the function "sorted" is more useful than a list method > >>"sorted" in a duck typing language. > > > > > > I don't see what this has to do with "duck typing"? sorted() is simply > > a generic function accepting different types. I'm not aware that > > sorted() requires a specific interface of those types it accepts. > > > Just because you aren't aware of something doesn't stop it being true. > The argument must be iterable, and there's a specific protocol for that. > > > >>The function sorted works on all iterators. I can do: > >> > Ah, so you *were* aware of it. I already responded to it two days ago in the reply to Terry. No need to rehash that. > >> > >def t(n): > > for i in range(n): > >yield i > >... > >print sorted(t(5)) > >> > >>and have it work. > >> > >>If sorted were a method of a class - the it'd have to be implemented > >>again for every class iterable class. Either that, or you'd have to > >>create an abstract parent of all iterable classes to add it to - which > >>seems more appropriate for a B&D language than Python. > > > > > > Instead of extending a class hierarchy it might even be possible to > > hook a trait into the class by means of a __traits__ attribute. > > > > http://fsl.cs.uiuc.edu/~mhills/presentations/TraitsPresentation.pdf > > > > Generators as well as lists and tuples would provide a sortable trait. > > The sorted() function could remain available for convenience. > > > The advantage being ... ? Perhaps you have just discovered a really > interesting hammer, and are seeing this problem as a nail? I also responded to traits as nice-to-have but not essential. And please don't aggressively consider me as childish as you might be yourself. Adding a __traits__ attribute should enable the user adding methods to builtins in a safe manner. This has the advantage that one can apply methods to string or integer literals or even replace methods without touching the C sources. A very typical use case is integer representation. In 95% of all my business applications I don't have much use for decimal integer representation but want a hex rep in different variants: >>> 0x0F # current rep 15 >>> int.__traits__.append(HexRepTrait) # used for delegation of # __repr__ to the Trait >>> int.configure_format(HexRepTrait.HEXFORM_STD) # configure_format is a # hooked trait method >>> 0x0F 0F >>> 2*0x800 10 00 >>> print 700 02 BC I know I can write wrapper classes, because I do this all the time, but that's not the point: Python is essentially not about boiler-plate. And no, I also don't want to fight for each method and keyword with Guido. > > > >>And even if you do add the abstract class, how do you make my example > >>work without explictly converting the iterator to a list type? > > > > > > I don't know how sorted() is implemented? A naive implementation would > > in fact be nothing else then: > > > > def sorted(iter): > > l = list(iter) > > l.sort() > > return l > > > > Kay > > > That would indeed be a naïve implementation. And that's the real implementation: static PyObject * builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs; PyObject *callable; static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0}; long reverse; if (args != NULL) { if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted", kwlist, &seq, &compare, &keyfunc, &reverse)) return NULL; } newlist = PySequence_List(seq); if (newlist == NULL) return NULL; callable = PyObject_GetAttrString(newlist, "sort"); if (callable == NULL) { Py_DECREF(newlist); return NULL; } newargs = PyTuple_GetSlice(args, 1, 4); if (newargs == NULL) { Py_DECREF(newlist); Py_DECREF(callable); return NULL; } v = PyObject_Call(callable, newargs, kwds); Py_DECREF(newargs); Py_DECREF(callable); if (v == NULL) { Py_DECREF(newlist); return NULL; } Py_DECREF(v); return newlist; } The crucial steps are the conversion from args to seq, the conversion from seq to newlist and finally calling PyObject_Call(callable, ...) where callable stores the sort method of newlist. By the way I don't see much use in implementing this trivial wrapper function in C except for the joy of refcounting ;) And now we take a look on how the PyPythonistas implemented sorted(): def sorted(lst, cmp=None, key=None, reverse=None): "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" sorted_lst
regex re.search and re.match
in the regex module re: Note: Match() is not exactly equivalent to Search() with "^". For example: re.search(r'^B', 'A\nB',re.M) # succeeds re.match(r'B', 'A\nB',re.M) # fails if without the re.M, would re.search and re.match be equivalent? i wish to spruce up the rewritten re-module doc http://xahlee.org/perl-python/python_re-write/lib/module-re.html with people's help. if at the end it is good, i hope it can find its way into the official doc. Xah [EMAIL PROTECTED] ∑ http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: List of integers & L.I.S. (SPOILER)
Tim Peters; INCREDIBLE~ > 241433 2005-09-11 04:23:40 Tim Peters accepted 3.44 7096 PYTH BRAVO! I just wonder have I grey cells enough for to understand how your algo works... and hopefully it's not your last solved problem on the contester. > I'm pretty sure they're using > slower HW than mine (3.4 GHz P5). As I mentioned before their 4 identical machines are PIII Xeon 700MHz. PS: each accepted solution automatically gets into "Best Solutions" list. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about consistency in python language
> Also, you shouldn't use "1", I mean "l", as a variable name. It gets confusing > because "l", I mean "1", looks a lot like "1", I mean "l". I have seen the same warnning above significantly several times. Is this problem originally came from the similarities between 'l' and '1' or from bad looking news-browser? Forgive me if it is out of your interests. -James GOLD -- http://mail.python.org/mailman/listinfo/python-list
Re: issue with string.Template
Michele Simionato wrote: from string import Template as T T("$obj").substitute(obj=()) > TypeError: not enough arguments for format string > So, take this as a bug report if the behavior is not intended and > as a feature request if the current behaviour is the intended > one ;) I vote for bug report. The need to habitually wrap any tuple arguments into another 1-tuple is clearly at odds with the goal to simplify string interpolation. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: getting words from readline
Ouch. That is simple with .split I must have got confused amongst slice re etc. searching searching. Thanks folks. Painless. -- http://mail.python.org/mailman/listinfo/python-list
issue with string.Template
This is somewhat in between a bug report and a feature request. I was using the new string.Template class and I have run into a few issues that I traced back to the usage of the idiom '%s' % val in the 'convert' helper function in Template.substitute. I do not understand why '%s' % val was used instead of just str(val). '%s' % val in unfortunate since it results in the following surprising (for me) behavior: >>> from string import Template as T >>> T("$obj").substitute(obj=("hello",)) 'hello' [not '("hello",)'] >>> T("$obj").substitute(obj=()) TypeError: not enough arguments for format string [not '()'] Is this intended behavior? It is surprising since it is different from what one would expect from old-fashioned string interpolation >>> "%(obj)s" % dict(obj=("hello",)) "('hello',)" >>> "%(obj)s" % dict(obj=()) '()' which is the behaviour I find most useful. Also, I do not like that different expressions such as T("$obj").substitute(obj=("hello",)) and T("$obj").substitute(obj="hello") give the same output (this potentially hides type bugs). So, take this as a bug report if the behavior is not intended and as a feature request if the current behaviour is the intended one ;) Michele Simionato P.S. at the end, the problem is that string interpolation with positional arguments is somewhat of a hack, but fixing this will have to wait until Python 3000 ... -- http://mail.python.org/mailman/listinfo/python-list