IMDbPY 2.8
IMDbPY 2.8 is available (tgz, deb, rpm, exe) from: http://imdbpy.sourceforge.net/ IMDbPY is a Python package useful to retrieve and manage the data of the IMDb movie database about both movies and people. With this release some major bugs were fixed, especially in the http and sql data access systems; moreover FAQs about movies and airing dates about tv series can be retrieved. Platform-independent and written in pure Python (and few C lines), it can retrieve data from both the IMDb's web server and a local copy of the whole database. IMDbPY package can be very easily used by programmers and developers to provide access to the IMDb's data to their programs. Some simple example scripts are included in the package; other IMDbPY-based programs are available from the home page. -- Davide Alberani [EMAIL PROTECTED] [PGP KeyID: 0x465BFD47] http://erlug.linux.it/~da/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[ANN] Python 2.5 Quick Reference
Hi all, An updated version of the Quick Reference for Python 2.5 is available in different formats at http://rgruet.free.fr/#QuickRef. Please report errors, inaccuracies and suggestions to Richard Gruet (pqr at rgruet.net). Richard -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Defining classes
Steven Bethard wrote: How are you doing it currently? Here's a sort of minimalist option: class weeble(object): ... def __metaclass__(name, bases, bodydict): ... cls = type(name, bases, bodydict) ... cls.wumpus = 'brinjal', cls ... return cls ... weeble.wumpus ('brinjal', class '__main__.weeble') Of course, it still takes four lines and a metaclass... Well, 'type' is a metaclass, yes, but not a custom metaclass, so I would say that you are using the metaclass hook here, but not a real metaclass. Still waiting for class decorators ... Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, thread else
Fredrik Lundh [EMAIL PROTECTED] wrote: Gigs_ wrote: -- import thread the thread module should not be used directly by application programs; use the threading module instead. Ooops! - I am doing this, for long running stuff. I was aware of threading, but I could not spot significant differences in functionality, and thread seems to work, and so far I have not been bitten (I think). What are the dangers? (Apart from the BogeyMan that might come and munch my code...) - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: automatically grading small programming assignments
Hi Brian You could make great use of XML-RPC here. XML-RPC is /really/ easy to use. Here is a simple example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549 You put procedures on the server that will check the args against a the required result, and report back to the student whether it passes or fails. Here is another example using xml-rpc over https, for security: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 So, the idea is that the student calls a procedure on the xml-rpc server (which you set up), and passes his results as an argument, and your server procedure can return True or False. One benefit is that if you change the input to the tests, you need only update the server.Actually, you could let the procedures on the server accept test input and student results, and return True or False. This would be cool :) Caleb On Dec 14, 6:27 pm, Brian Blais [EMAIL PROTECTED] wrote: Hello, I have a couple of classes where I teach introductory programming using Python. What I would love to have is for the students to go through a lot of very small programs, to learn the basic programming structure. Things like, return the maximum in a list, making lists with certain patterns, very simple string parsing, etc. Unfortunately, it takes a lot of time to grade such things by hand, so I would like to automate it as much as possible. I envision a number of possible solutions. In one solution, I provide a function template with a docstring, and they have to fill it in to past a doctest. Is there a good (and safe) way to do that online? Something like having a student post code, and the doctest returns. I'd love to allow them to submit until they get it, logging each attempt. Or perhaps there is a better way to do this sort of thing. How do others who teach Python handle this? thanks, Brian Blais -- - [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Simple Way To Determine If File Is Executable
[Tim Daneliuk] I have a program wherein I want one behavior when a file is set as executable and a different behavior if it is not. Is there a simple way to determine whether a given named file is executable that does not resort to all the lowlevel ugliness of os.stat() AND that is portable across Win32 and *nix? I'm fairly certain the answer is no. What follows is a relatively low-level and certainly not portable discussion. The last couple of times this question came up on the list I looked into the implementation and experimented a bit but in short I would say that os.stat / os.access were near enough useless for determining executablility under Windows. That's not down to Python as such; it's simply passing back what the crt offers. Of course that raises the slightly wider issue of: should the Python libs do more than simply call the underlying crt especially when that's known to give, perhaps misleading results? But I'm in no position to answer that. I suggest that for Windows, you either use the PATHEXT env var and determine whether a given file ends with one of its components. Or -- and this depends on your definition of executable under Windows -- use the FindExecutable win32 API call (exposed in the win32api module of pywin32 and available via ctypes) which will return the executable for anything which has an association defined. So the executable for a Word doc is the winword.exe program. The executable for an .exe is itself. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing and reading variables to/from flat file
Hi Kevin The other posters helped you with configParser, which is what you wanted, i.e. text file access. However, you can also get persistance really cheaply with pickling, if you don't need the saved data to be text-editable: (from memory) verboseSettings = {} verboseSettings['Detailed'] = '-vv' verboseSettings['Basic'] = '-q' import cPickle # Save the data - Just give the dict! cPickle.dump(verboseSettings, file('prefs','w+')) # Load the data back - get the dict back verboseSettings = cPickle.load(file('prefs','r')) I recently did a ton of scientific data analysis looking for trends in 10 years of data for a petrochemical plant, and I learned just how convenient dicts and pickles can be to manage one's sanity :) Caleb On Dec 14, 4:31 pm, Kevin Walzer [EMAIL PROTECTED] wrote: I want to write some variables (user preferences, specifically) to a text file and then read the values from that file. Here is my code to write the data: verbosemodes= Detailed = -vv Basic = -q file = open('prefs', 'w') file.writelines(verbosemodes) file.close() And here is my code, in a separate module, to read the file and display the variable values: readfile = open('prefs').readlines() for line in readfile: print line print Basic Running the second module yields this error: Detailed = -vv Basic = -q Traceback (most recent call last): File readprefs.py, line 6, in module print Basic NameError: name 'Basic' is not defined Clearly the data is getting read (the lines are being printed), but the variable itself (Basic) is not being initialized properly. I'm not sure what I'm doing wrong here--can anyone point me in the right direction? Thanks. -- Kevin Walzer Code by Kevinhttp://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
connect from windows to linux using ssh
Hi Folks, How to connect from windows to linux using ssh without username/passwd. With this scenario, i need to write a program on python. Regards, Ramakrishna. -- http://mail.python.org/mailman/listinfo/python-list
Re: Validate XML against a set of XSD files, with Python
Stefan Behnel wrote: RelaxNG support in libxml2 is pretty much perfect, BTW. The *potential* issue I mentioned before with Relax NG validation in libxml2 does *NOT* exist. I double-checked with Jing and my RelaxNG file was indeed incorrect ... (the recursive reference outside elements kind of mistake). Jing more detailled error reports helped ... Mea Maxima Culpa. Wouldn't like to spread FUD :) Cheers SB -- http://mail.python.org/mailman/listinfo/python-list
Re: connect from windows to linux using ssh
[EMAIL PROTECTED] wrote: Hi Folks, How to connect from windows to linux using ssh without username/passwd. With this scenario, i need to write a program on python. Use ssh library http://cheeseshop.python.org/pypi/paramiko -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Ken Tilton wrote: Andrew Reilly wrote: That all looks like data. No, not reverse, the part you did not understand. I do not mean what the code was doing, I meant that it was code. Code is data is code - even in Python: skills_table = [ { title: Absolute Value, annotations: [Bleah bleah, ho hum, etc...], hints: [and so on, etc...], reverse : (lambda x: whatever(x)) }, { title: Square Root, annotations: [Bleah bleah, ho hum, etc...], hints: [and so on, etc...], reverse : (lambda x: someother(x)) }, # etc... ] Of course those lambdas are crippled in Python (and not really necessary in this bogus example)... But that's without trying to be clever: class AbsoluteValue: title=Absolute Value annotations=[Some list, goes here] @classmethod def reverse(cls, *args): # I didn't understand what your code was doing pass defskill(AbsoluteValue) That would be a reasonable place for a pie decorator on a class, but I guess that's not allowed. I doubt this second example would be considered Pythonic in any case... Couldn't you do that with a table containing those fields, and key it off the defskill argument (or even the title?) at startup? Not the code. In reverse. Why not? Python has plenty of other flaws that I can't happily work around, and I do think Lisp is more flexible. However, I think your example is readable enough with a data driven algorithm in most any popular language. All of the data is visible to the reverse(...) method. Maybe I missed something in your example, but I think you aren't trying hard enough. :-) The one I liked was: http://ll1.ai.mit.edu/shriram-talk.pdf If I ever fill in your RtL survey, I'll be citing that one as a turning point for me. Interpolation does not mean what you think it means. I'm sure he meant string interpolation, which is a common enough term in scripting languages nowdays. It would be easier to compare and contrast with the Python equivalent if someone had posted such, but your troops have fallen back to Fort So What? and pulled up the drawbridge. Oh God! Is it just me out here? And I'm not even a believer. Cheers. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I edit a PythonWin path to import custom built modules???
BartlebyScrivener wrote: Gabriel Genellina wrote: import sys print sys.path and see what's there. Yup. Did that before. That's what I mean. The d:\\python is there and it doesn't come from the PythonPath in my windows registry. Maybe it scans for any directory with python in the name? ['', 'C:\\WINDOWS\\system32\\python24.zip', 'd:\\python', 'C:\\Python24\\DLLs', 'C:\\Python24\\lib', 'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-tk', 'C:\\Python24\\Lib\\site-packages\\pythonwin', 'C:\\Python24', 'C:\\Python24\\lib\\site-packages', 'C:\\Python24\\lib\\site-packages\\win32', 'C:\\Python24\\lib\\site-packages\\win32\\lib', 'C:\\Python24\\lib\\site-packages\\wx-2.7.1-msw-ansi'] rd Hi rd, To revert back to my question, I wanted to add a new path to my PythonWin IDE to access modules which are in folders other than normal python paths. Here, I need to put my modules in different folders since it is a request of the user. I tried to create a new PYTHONPATH in the environmental variables section, which did not work . So, is there any way where I can temporarily append the new path/s, where the PythonWin interpreter would look during run time and discard after the interpreter is closed. For example, my main program ATS.py will be put in the folder D:\\dSPACE\ATS\ and my modules will be put in other folders inside the folder ATS, D:\\dSPACE\ATS\ Level Regulation, D:\\dSPACE\ATS\ Curve Detection and so on. So, I would like to tell the interpreter to look in to these folders to import the modules. Is that possible??? Regards, Mohan -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditional iteration
This why I prefer functional programming constructs for my list/sequence processing needs. is_true = lambda x: x 0 map(process_list, filter(is_true, [-2, -1, 0, 1, 2, 3, 4])) at wrote: I would like to spark the discussion about the following syntax problem I encounter. THE PROBLEM I have a lot times the following code: for x in [-2, -1, 0, 1, 2, 3, 4]: if x 0: ... more code... It is not the addional line containing 'if x 0:' that bothers me, but the additional indentation. THE SOLUTION More pythonic in view would be: for x in [-2, -1, 0, 1, 2, 3, 4] if x 0: ... more code ... This blends basically [x for x in [-2, -1, 0, 1, 2, 3, 4] if x 0] and x = y if x 0 else 10 EXTENDING And maybe a few usefull variants, like: for x in [-2, -1, 0, 1, 2, 3, 4] if x 0 else -x: ... more code ... In this case x will be 2, 1, 0, 1, 2, 3, 4. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I edit a PythonWin path to import custom built modules???
At Friday 15/12/2006 06:46, mohan wrote: To revert back to my question, I wanted to add a new path to my PythonWin IDE to access modules which are in folders other than normal python paths. Here, I need to put my modules in different folders since it is a request of the user. I tried to create a new PYTHONPATH in the environmental variables section, which did not work . You can do that directly inside PythonWin, using the Tools menu. So, is there any way where I can temporarily append the new path/s, where the PythonWin interpreter would look during run time and discard after the interpreter is closed. You could modify sys.path at runtime, appending directories if needed. But the package solution below is much better. For example, my main program ATS.py will be put in the folder D:\\dSPACE\ATS\ and my modules will be put in other folders inside the folder ATS, D:\\dSPACE\ATS\ Level Regulation, D:\\dSPACE\ATS\ Curve Detection and so on. So, I would like to tell the interpreter to look in to these folders to import the modules. First, remove all spaces from directory names. Then make them normal packages (an empty __init__.py may be enough) so you can write, in ATS.py: from LevelRegulation import whatever from CurveDetection.MyModuleName import MyClass etc. -- Gabriel Genellina Softlab SRL __ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ¡gratis! ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar -- http://mail.python.org/mailman/listinfo/python-list
OT - Looking for DrPython project help
Sorry for posting that, if you are not intersted, please ignore my post. I'm looking for person(s), which are interested in testing and possibly bug fixing for DrPython (hosted on Sourceforge) in general and with a certain focus for Linux. Sometimes, texts in dialogs are not entirely visible, some are without sizers, some crashes, plugin testing, ... If you have interest, please send a message to Open Discussion: http://sourceforge.net/forum/forum.php?forum_id=283802 -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Ken Tilton [EMAIL PROTECTED] writes: Steven D'Aprano wrote: If that's the best example of what macros can be used for, frankly I'm unimpressed. We're shocked. Don't anyone tell him about LOOP. -- This post uses 100% post consumer electrons and 100% virgin photons. At 2.6 miles per minute, you don't really have time to get bored. --- Pete Roehling on rec.motorcycles I bump into a lot of veteran riders in my travels. --- David Hough: Proficient Motorcycling -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Wolfram Fenske [EMAIL PROTECTED] writes: Paul Rubin http://[EMAIL PROTECTED] writes: Wolfram Fenske [EMAIL PROTECTED] writes: Yes, I wrote about it in another post. It was introduced in Python 2.5. And if it hadn't been I'd still have to write code like this. You could do something with decorators that's not too bad. You'd end up writing: @withConnection def some_func(): do_whatever_stuff () Yes, now I can. But I had to wait until Python 2.4 to be able to that. What I like so much about Lisp macros is that they allow me to make these changes myself. Besides, who wants to write production code in a language that keeps changing? It's enough work just keeping up with new libraries. -- This post uses 100% post consumer electrons and 100% virgin photons. At 2.6 miles per minute, you don't really have time to get bored. --- Pete Roehling on rec.motorcycles I bump into a lot of veteran riders in my travels. --- David Hough: Proficient Motorcycling -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Steven D'Aprano [EMAIL PROTECTED] writes: How am I being silly? Do you not believe that people write case blocks with fifty tests? Okay, how about twenty? Ten? Eight? You should check out generic functions in CLOS. Rather than writing a ridiculously long case block, you can use EQL specialized functions. It's a great way to do dispatch. -- This post uses 100% post consumer electrons and 100% virgin photons. At 2.6 miles per minute, you don't really have time to get bored. --- Pete Roehling on rec.motorcycles I bump into a lot of veteran riders in my travels. --- David Hough: Proficient Motorcycling -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging module: problem with some mapping keys
On Dec 14, 6:41 pm, Peter Otten [EMAIL PROTECTED] wrote: Tekkaman wrote: lib is a symlink to lib64 So my initial diagnosis was correct. Unfortunately I can no longer recommend that you remove the symlink... Yes. What I really meant in my first reply was it's not a symlink in the script's own directory: I didn't suspect that a symlink at any level in the path between the script and the logging module would break findCaller(). Putting /usr/lib64/python2.4 as the first entry into your PYTHONPATH environment variable might fix the problem (the idea is that /usr/lib64/python2.4 precedes /usr/lib/python2.4 in sys.path and is therefore used for the import of the logging package). Thanks, I'll check it out. Anyway, since this is a hack, you think this behaviour should be reported as a bug? Peter T. -- http://mail.python.org/mailman/listinfo/python-list
Mail System Error - Returned Mail
The message was not delivered due to the following reason(s): Your message could not be delivered because the destination computer was not reachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message could not be delivered within 2 days: Host 121.23.77.116 is not responding. The following recipients could not receive this message: python-list@python.org Please reply to [EMAIL PROTECTED] if you feel this message to be in error. -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditional iteration
At Friday 15/12/2006 06:51, mystilleef wrote: This why I prefer functional programming constructs for my list/sequence processing needs. is_true = lambda x: x 0 map(process_list, filter(is_true, [-2, -1, 0, 1, 2, 3, 4])) Be aware that map, filter, and reduce may be dropped in Python 3000. http://www.artima.com/weblogs/viewpost.jsp?thread=98196 (and I won't miss them if gone) -- Gabriel Genellina Softlab SRL __ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ¡gratis! ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Delaney, Timothy (Tim) wrote: Ken Tilton wrote: But this is not a case where a function can't handle the job. Is, too. And Ken moves one step closer towards Python ... http://www.google.com.au/search?q=monty+python+argument+sketch Tim Delaney is it time to mention the storm troopers and A H*? This thread certainly needs shutting down :) -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Roundtrip SQL data especially datetime
When getting data from a database using the dbapi and an SQL query, how do you in general round trip the data? Especially date-time? An SQL datetime column translates nicely into a Python datetime (surprise), which then translates into a string like '2005-08-03 07:32:48'. No problem with that -- all works quite nicely, until you try to put data back the other way. There is no obvious way to parse that string back into a datetime, and having done so no obvious way to push that back into a SQL datetime column. Am I missing something? [I would particularly like to avoid getting trapped by SQL local settings too.] DavidY -- http://mail.python.org/mailman/listinfo/python-list
Re: Property error
What version of Python? Most recent versions don't need the Hi, thanks for the help! I am using 2.5 version and i think i like more the @property decorator instead of the property(...) syntax. Is the code changing much using @property ?? Thanks again! -- http://mail.python.org/mailman/listinfo/python-list
concatenating strings
hello! since i am a py noob, please bear with me ; ) how is it possible to concat a string and an integer in a print-command? i've tried print This robot is named %s. The current speed setting is %d, and %s has a lifetime of %d % (self.name , self.speed , self.name) as well as print This robot is named %s. The current speed setting is %d, and %s has a lifetime of %d self.name % self.speed % self.name though nothing works out... background is a class named Robot with members speed, name, etc... tia, Erich -- http://mail.python.org/mailman/listinfo/python-list
Re: concatenating strings
EHC a écrit : hello! since i am a py noob, please bear with me ; ) how is it possible to concat a string and an integer in a print-command? i've tried print This robot is named %s. The current speed setting is %d, and %s has a lifetime of %d % (self.name , self.speed , self.name) Four % formating with only three arguments to format. It cannot work... print This robot is named %s. The current speed setting is %d, and %s has a lifetime of %d % (self.name , self.speed , self.name, self.lifetime) ... background is a class named Robot with members speed, name, etc... May try this too: print This robot is named %(name)s. The current speed setting is %(speed)d, and %(name)s has a lifetime of %(lifetime)d % self.__dict__ [note: liftefime may be a dynamically calculated value, and should be providen via an accessor attribute] -- http://mail.python.org/mailman/listinfo/python-list
Re: automatically grading small programming assignments
Dan Bishop wrote: On Dec 14, 8:36 pm, Brian Blais [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Then on your PC you can run a script that loads each of such programs, and runs a good series of tests, to test their quality... What happens if someone-- perhaps not even someone in the class-- does some version of os.system('rm -Rf /') ?I was thinking of including a dummy os.py and sys.py, so import os, and import sys would fail. Would this work? How would they access their command-line arguments without sys.argv? the types of assignments that I am envisioning (finding the maximum in a list, parsing strings, etc.) will not need anything offered in os or sys. Certainly, if they were needed, another solution would need to be found. bb -- - [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
Re: Property error
Your example Dennis, work as expected. I understand the mistake i have made. But when i try to fix the original code usihn @property now, it gives me the same error. So, here it is: class Person(object): _age = 0 @property def age(): def fget(self): return self._age def fset(self, value): self._age = value me = Person() me.age = 34 print me.age I am sure it is something very obvious but my skills does not (yet) enable me to figure this out,,, -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing and reading variables to/from flat file
Geoffrey Clements: readfile = open('prefs').readlines() for line in readfile: print line eval(line) print Basic Instead of using eval, using a plain dict may be a better solution. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging module: problem with some mapping keys
Tekkaman wrote: Putting /usr/lib64/python2.4 as the first entry into your PYTHONPATH environment variable might fix the problem (the idea is that /usr/lib64/python2.4 precedes /usr/lib/python2.4 in sys.path and is therefore used for the import of the logging package). Thanks, I'll check it out. Anyway, since this is a hack, you think this behaviour should be reported as a bug? Yes, that's a good idea. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: concatenating strings
thank you, i just plainly overlooked it ; ) now it works -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Gabriel Genellina wrote: You can even make S = cT (c=ligth of speed in void space). The choice of fundamental units is rather arbitrary, and can be reduced further to only 1 fundamental unit and even NO fundamental units. I once heard mention of a system of units in use at one time with the odd feature that capacitance came out in units of length. Picture the scene: Hobbyist walks into Dick Smith store and says I'd like a 5cm capacitor, please. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Ken Tilton wrote: So this: (defmethod tf-reverse (id (eql ',sub-id)) resx (drv-opnds tf drv)) ,@reverser) becomes this: (defmethod tf-reverse ((id (eql ',sub-id)) tf drv aux (opnds (drv-opnds tf drv))) (loop for resx in (results drv) ,@reverser)) I don't see why you can't just write a function that loops over the results and calls the user's reversal function for each one. def reverse_multiple(skill, resx_list, opnds): for resx in rex_list: skill.reverse(resx, opnds) There's no need to macro-expand this code into every reversal function, when it can be done once as part of the framework that calls the reversal functions. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Ken Tilton wrote: The reason I post macro expansions along with examples of the macro being applied is so that one can see what code would have to be written if I did not have the defskill macro to write them for me. It seems to me your brain is somewhat stuck on the use of macros. You're looking at the expansion of your macro and assuming that you'd have to write all that code by hand if you didn't have macros. You're not thinking about alternative approaches, which could just as well be used in Lisp as well as Python, that are just as compact yet don't make use of macros. Unless there's something very subtle that I'm missing (I can't claim to follow exactly what all the code you posted does in detail) I haven't seen anything that couldn't be done quite reasonably with an appropriate data structure and ordinary functions and methods operating on that data structure. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
[EMAIL PROTECTED] wrote: Neil Cerutti wrote: On 2006-12-13, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Expressions keep the same meaning even if you have to start breaking them across lines, etc. Yes, it's the same way in Python. Of course, not everything is an expression in Python, so it's not saying quite as much. I fail to see how it is the same in Python. Probably what Neil is referring to is the fact that in Python, *within an expression*, indentation is not relevant. If you put parens around the whole expression, you can split it across lines however you like, and indent all the lines after the first one however you like, and it makes no difference. You could probably even use your Lisp-aware auto-indenter on the expression and it would do something reasonable. It's only *statement* nesting that's determined by relative horizontal position (which is a better way of thinking about it than whitespace -- the whitespace is only there to get things into the right position). And statements normally occupy one or more entire lines. How does a manual correction process come out as simple as don't bother fixing the indentation if you don't care.? I think the point is that correcting indentation in Python is the equivalent of fixing misplaced parentheses in Lisp, and that they're about equally difficult. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
[EMAIL PROTECTED] wrote: I wrote my first Python in a non-Python-aware editor, and somehow had swapped tabs and spaces; when I moved it to IDLE---the indentation *looked fine* but was invisibly weird. That can admittedly be a problem. It would help if the parser complained by default about mixed use of tabs and spaces in a single file, instead of silently assuming tab stops every 8 spaces (an historical misfeature that we still have for the time being). Probably this will change in Python 3.0. Personally I find Python pleasant enough to work with that I'm willing to put up with the odd screwup like that happening now and then. And they really don't happen all that often -- once you've experienced it a few times, you learn how to guard against it and get better at fixing it when it does happen. I will even admit that white-space significance does not materially increase errors among experienced Pythonistas. What it isn't is some kind of miraculous invention that saves programmers from ever making mistakes that are common in other languages, We don't claim that -- only that it's not the unmitigated disaster than some people assume it will be without ever having tried it. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
[EMAIL PROTECTED] wrote: Neil Cerutti wrote: The parenthesis I added means I don't have to use the new-line escape character (\), either. Is this so unconscious that you don't recognize you are doing it, even though you take a sentence to explain what you had to do to work around it? Yes, it is pretty unconscious. We all do many things unconsciously in everyday life that would take at least one sentence to explain to someone else if we had to think about it. Besides, in many cases the required brackets are already there -- e.g. if it's a list, or a function call with many arguments -- in which case you don't have to add anything at all. Adding parentheses ... all this is a burden specific to Python. As opposed to Lisp, where all you have to do is use parentheses... oh, er... By the way, you guys seem fixate on the parentheses of Lisp without having the experience I don't know about the other Pythonistas in this discussion, but personally I do have experience with Lisp, and I understand what you're saying. I have nothing against Lisp parentheses, I just don't agree that the Lisp way is superior to the Python way in all respects, based on my experience with both. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Ken Tilton wrote: What if it turns into an SQL lookup during refactoring? If the macro can produce SQL code, then whatever interprets the table can produce SQL code as well. If you're thinking of the macro taking apart the user's reverse function (rather than just wrapping it) and somehow translating it into SQL, well... a macro *could* do that, but it would be an awfully hairy thing to do, especially if the user is allowed to write arbitrary Lisp code in the body of his function (as it seems he is, in your example). A better way would be to design an abstract API for the user to use in his reverse functions. Then you can just re-implement the functions making up the API so that they do SQL queries instead of whatever they were doing before. No macro processing needed then. The last example showed the macro inserting code to magically produce a binding inside the reverse function. Are you sure? It looked to me like it was adding code *around* the reverse function, not inside it. I posted a Python function that achieves the same thing by calling the existing reverse function. It would be easier to compare and contrast with the Python equivalent if someone had posted such, but your troops have fallen back to Fort So What? and pulled up the drawbridge. I'm still trying, but some of the code you posted is rather impenetrable without knowing a lot more about the details of your system. I'm doing my best to show some Python demonstrating the gist of what could be done. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: CLPython (was Re: merits of Lisp vs Python)
Willem Broekema wrote: I guess in part it's because there are not that many people really into both Python and Lisp, and those who are might not find this an interesting project because there is nothing wow to show, yet. Another reason (or maybe the reason for the reason) is that people are usually interested in Python because it's a relatively simple and lightweight thing. Having to install a complex and heavyweight thing like a Common Lisp system just to be able to program in Python doesn't seem like a good deal. It might become a good deal if you could then compile the Lisp and get a lean, efficient binary executable out of it. But that's going to require much more than just a straightforward translation from Python to Lisp. If CLPython starts to show signs of making progress in that direction, then it could start to get interesting. Although I think I'd rather target Scheme than CL if I were doing it -- cleaner language, small yet still extremely good implementations available. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Missing __length_hint__ in __getitem__ iterator
Hello, given the following object: class A(object): ... def __getitem__(self, idx): ... if idx = 10: raise IndexError ... return idx ... def __len__(self): ... return 10 ... I noticed that the iterator that Python constructs: a = A() i = iter(a) dir(i) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__len__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'next'] does not have a __length_hint__ method. Is this just a missing optimization, or there is a deep semantic reason for which a __length_hint__ could not be constructed out of the __len__ result? -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
Re: skip last line in loops
Fredrik Lundh wrote: [EMAIL PROTECTED] wrote: how can i skip printing the last line using loops (for /while) eg for line in open(file): print line. I want to skip printing last line of the file. do it lazily: last_line = None for line in open(file): if last_line: print last_line last_line = line or just gobble up the entire file, and slice off the last item: for line in list(open(file))[:-1]: print line /F hi would it be a problem with these methods if the file is like 20Gb in size...? -- http://mail.python.org/mailman/listinfo/python-list
Re: Property error
king kikapu wrote: Your example Dennis, work as expected. I understand the mistake i have made. But when i try to fix the original code usihn @property now, it gives me the same error. So, here it is: class Person(object): _age = 0 @property def age(): def fget(self): return self._age def fset(self, value): self._age = value me = Person() me.age = 34 print me.age I am sure it is something very obvious but my skills does not (yet) enable me to figure this out,,, @decorator def f(): # ... is the same as def f(): # ... f = decorator(f()) What happens when your age() function is invoked? There is no explicit return statement, so None is implicitly returned, and age = property(age()) is the same as age = property(None) i. e. you get a property with None as the getter. What you want is def star_property(f): ... return property(**f()) ... class Person(object): ... _age = unknown ... @star_property ... def age(): ... def fget(self): ... return self._age ... def fset(self, value): ... self._age = value ... return locals() ... person = Person() person.age 'unknown' person.age = 42 person.age 42 However, that is rather hackish, and I recommend that you stick with the standard approach given by Dennis and limit the use of property as a decorator to read-only attributes: class Forever42(object): ... @property ... def age(self): return 42 ... Forever42().age 42 Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing __length_hint__ in __getitem__ iterator
Giovanni Bajo wrote: Hello, given the following object: class A(object): ... def __getitem__(self, idx): ... if idx = 10: raise IndexError ... return idx ... def __len__(self): ... return 10 ... I noticed that the iterator that Python constructs: a = A() i = iter(a) dir(i) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__len__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'next'] does not have a __length_hint__ method. Is this just a missing optimization, or there is a deep semantic reason for which a __length_hint__ could not be constructed out of the __len__ result? It's there, just not doctored into the dir() output: class A(object): ... def __getitem__(self, index): return index ... def __len__(self): return 42 ... iter(A()).__length_hint__ built-in method __length_hint__ of iterator object at 0x401d558c iter(A()).__length_hint__() 42 Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Property error
Peter Otten wrote: @decorator def f(): # ... is the same as def f(): # ... f = decorator(f()) ^^ Nope, f is not called here. (Think of staticmethod). Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Property error
king kikapu wrote in news:1166181267.949316.197360@ 16g2000cwy.googlegroups.com in comp.lang.python: I am sure it is something very obvious Yes, property is *NOT* a decorator, it can only be used as a decorator in the one case that is mentioned in the docs: quote href=http://docs.python.org/lib/built-in-funcs.html#l2h-57; If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator: class Parrot(object): def __init__(self): self._voltage = 10 @property def voltage(self): Get the current voltage. return self._voltage /quote Note the use of read-only in the above description and that the decorated function (voltage) *is* the properties fget function. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
AI library
I thought about an AI library for python. This is the possible structure I came up with. Are there any thoughts about it? ailib/ search.py class State: represents an immutable state of a problem def __str__(self): pass def __hash__(self): pass class StateSpace: represents a traversable collection of states def start(self): returns a list of initial states pass def follow(self, state). returns a list of states that follow after state pass def search(self, order=none): returns an iterator over all states according to order order can be a constant (depth, breadth, incdepth) or a heuristic. If none some default search will be used. pass def __iter__(self): return self.search() class Heuristic: def follow(self, state): returns a list of states probably closer to the solution than s pass class Graph(StateSpace): def __init__(self, paths) paths is a set of tuples (nodeFrom, nodeTo, weight) pass def a-star(self, nodeFrom, nodeTo): searches the shortest path (minimal weight) from nodeFrom to nodeTo. pass plan.py class State(search.State): represents a state of the world that can be changed through action. pass class Agent(search.StateSpace): For any given state an Agent has a set of possible actions that transform the initial state into a subsequent state. def perceive(self): returns the state of the world the agent perceives to be in. pass def actions(self, state): returns an iterator over actions available in the given state. pass def __iter__(self): return self.actions(self.perceive()) def plan(self, state, currentState=none): returns a sequence of actions that are supposed to transform the currently perceived state of the world into the desired state. if currentState==none: currentState = self.perceive() else: pass logic.py class Symbol: a Symbol that can be bound to a value or unbound. def bound(self): returns true if the symbol is bound. def value(self): if bound returns the value. class Function: transforms a list of symbols into another symbol. def __init__(self, *symbols): self.symbols = symbols def __call__(self): returns some symbol. pass class Predicate: either is or is not valid for a given list of symbols def __init__(self, *symbols): self.symbols = symbols def __call__(self): returns true or false pass class Junctor: a relation between predicates deriving a truth value from the truth values of the predicates def __init__(self, *predicates): self.predicates = predicates def __call__(self): returns some truth value pass class Quantifier: somehow binds symbols. pass class Clause: A quantified junctor. pass class Axioms: A list of clauses def consistent(self): returns true if the list of axioms is consistent pass def valid(self, clause, bind=true): returns true if the clause is consistent with the set of axio If bind is true, any unbound symbol will be bound to a value if pass statistics.py class Entity: bearer of statistically relevant features. pass class Set: set of entities. defines usual statistical functions def __iter__(self): iterate over all entities. def avg(self, feature): returns the average of the given feature of all entities. pass # likewise other functions def entropy(self, a, b): returns the level of randomnes (0..1) between the given feature pass def correlates(self, a, b, e=0.5): return self.entropy(a, b) e def mine(self): returns the tuple of features with the least entropy. game.py
Re: Property error
king kikapu wrote: Hi to all, i am trying to use properties in Python and i am sure i have made something wrong with the below code but i just cannot see what it is. Can anyone please help me on this ? The code is : class Person(object): age = 0 @property def age(): def fget(self): return self.age def fset(self, value): self.age = value me = Person() me.age = 34 print me.age and i am getting the error: File C:\projects\Python\p2.py, line 12, in module me.age = 34 AttributeError: can't set attribute What exactly i am doing wrong ?? This will not work. There are some versions of a property decorator flowing around that allow you to do a similar thing, like class Person(object): age = 0 @Property def age(): def fget(self): return self.age def fset(self, value): self.age = value return locals() but here, Property is not the built-in property function. It is impossible to use the built-in property function as a decorator to create a property that isn't read-only. Georg -- http://mail.python.org/mailman/listinfo/python-list
cxfrozen linux binaries run on FreeBSD?
When i freeze a python app (simple - no strange sys calls) for x86 Linux, does this stuff run well also on x86 FreeBSD? Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: skip last line in loops
[EMAIL PROTECTED] wrote: do it lazily: last_line = None for line in open(file): if last_line: print last_line last_line = line or just gobble up the entire file, and slice off the last item: for line in list(open(file))[:-1]: print line /F hi would it be a problem with these methods if the file is like 20Gb in size...? The second one would be a problem, since it creates a list containing all the lines of the file. Use the lazy approach. -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: need clarification with import statements
Hi John, 1. Your directory/package hierarchy is far too complicated. Flatten it. Ok. 2. You have circular references: the others module will import from utils, but utils wants to import from others. This is prima facie evidence that your modules are not structured properly Yes, that's why I asked the question in fact, circular references are a bit hazardous. . Rule 1: Modules should contain /related/ classes and functions. Rule 2: A graph of what imports what should not have loops. Consider combining others and utils -- does that make sense? Yes, I can combine them as they need eachother. Another alternative: split out those some functions of myutils.py (ie myutils_func1 and myutils_func2) into a fourth module. This module might be the nucleus of a tool-kit of miscellaneous functions that you might import in /any/ app -- in that case, move it outside the current package. Good idea indeed, Thanks for all, 6TooL9 -- http://mail.python.org/mailman/listinfo/python-list
Re: automatically grading small programming assignments
Brian Blais wrote: Dan Bishop wrote: On Dec 14, 8:36 pm, Brian Blais [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Then on your PC you can run a script that loads each of such programs, and runs a good series of tests, to test their quality... What happens if someone-- perhaps not even someone in the class-- does some version of os.system('rm -Rf /') ?I was thinking of including a dummy os.py and sys.py, so import os, and import sys would fail. Would this work? How would they access their command-line arguments without sys.argv? the types of assignments that I am envisioning (finding the maximum in a list, parsing strings, etc.) will not need anything offered in os or sys. Certainly, if they were needed, another solution would need to be found. If you do a search on the web, you will find that there are many other security problems in Python that can not be prevented by simply including dummy modules for os and sys. Brett Cannon's PhD thesis is, afaik, based on looking at ways of creating a secure Python environment. Other suggestions mentioned before (like running in a virtual environment) might be the best way to go for now. Having the user run the program on their own machine (like would be done with the current version of Crunchy already mentioned in this thread) would keep yours safe. Crunchy's doctest feature could be easily modified so that it logs the number of attempts and mail the results to a given address. André -- http://mail.python.org/mailman/listinfo/python-list
Re: Property error
Peter Otten wrote: @decorator def f(): # ... is the same as def f(): # ... f = decorator(f()) What happens when your age() function is invoked? There is no explicit return statement, so None is implicitly returned, and age = property(age()) is the same as age = property(None) As Georg pointed out, this is all wrong. As age is not called the age function becomes the getter. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, thread else
Fredrik Lundh wrote: did you write that yourself, or did you find it in some book or article? This is the example from programming python 2nd book, I use this just for learning -- http://mail.python.org/mailman/listinfo/python-list
Re: CLPython (was Re: merits of Lisp vs Python)
greg wrote: Willem Broekema wrote: I guess in part it's because there are not that many people really into both Python and Lisp, and those who are might not find this an interesting project because there is nothing wow to show, yet. Another reason (or maybe the reason for the reason) is that people are usually interested in Python because it's a relatively simple and lightweight thing. I think it's more likely that the Lisp people wonder why you'd want to write anything other than Lisp (and they're all supposedly too busy doing other things, anyway, like rewriting their own version of reddit.com), whereas the Python people either haven't heard about it, aren't really interested because they believe other projects (eg. PyPy) will deliver the same benefits (which probably won't be the case entirely), or don't have the means to either run and experiment with it or to help out. Having to install a complex and heavyweight thing like a Common Lisp system just to be able to program in Python doesn't seem like a good deal. There seems to be a fairly high intuitive similarity between various Common Lisp concepts and various Python concepts, although one can only make best use out of Common Lisp features (or the features of any particular platform) if the correspondence is sufficiently high. I suppose the argument that one can write extensions in Lisp rather than C may be enticing, but one returns to the why write anything other than Lisp argument at this point. There may be an argument for having CLPython as an embedded application scripting language, but again the Lisp camp have often advocated Lisp for that role, too. It might become a good deal if you could then compile the Lisp and get a lean, efficient binary executable out of it. But that's going to require much more than just a straightforward translation from Python to Lisp. Indeed. If CLPython starts to show signs of making progress in that direction, then it could start to get interesting. Although I think I'd rather target Scheme than CL if I were doing it -- cleaner language, small yet still extremely good implementations available. Well, there are some open source Common Lisp implementations around, despite the obvious bias in certain circles to encourage everyone to use the proprietary implementations instead, and things like SBCL are only a simple package manager install away. Meanwhile, there was an implementation of Python for Scheme, but I don't think the developers took the idea much further after presenting it at PyCon a few years ago. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: skip last line in loops
[EMAIL PROTECTED] wrote: Fredrik Lundh wrote: [EMAIL PROTECTED] wrote: how can i skip printing the last line using loops (for /while) eg for line in open(file): print line. I want to skip printing last line of the file. do it lazily: last_line = None for line in open(file): if last_line: print last_line last_line = line or just gobble up the entire file, and slice off the last item: for line in list(open(file))[:-1]: print line /F hi would it be a problem with these methods if the file is like 20Gb in size...? See the documentation for xreadlines. James -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
Maybe there would be less dispute if this dogma/convention(?) Tuples are for heterogeneous data, list are for homogeneous data would be written down somewhere in the tutorial, reference or in PEP8, so people would be aware of it. And can somebody explain what is exactly meant with homogenous data? That the type of the elements is the same in some technical or philosophical meaning? Concretely speaking, which data type should I use for coordinate tuples? Usually, tuples are used. Does this mean that I should better use lists from now on because all the components have the same type? -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditional iteration
In [EMAIL PROTECTED], Gabriel Genellina wrote: Be aware that map, filter, and reduce may be dropped in Python 3000. http://www.artima.com/weblogs/viewpost.jsp?thread=98196 (and I won't miss them if gone) There are `imap` and `ifilter` in the `itertools` module. I guess/hope they will stay in Python 3000. And Guido already said that ``lambda`` will stay, so maybe he changes his mind about `map` and `filter` too. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: No latin9 in Python?
Martin v. Löwis wrote: While you are at it, you'll notice that the current version of the character-sets database lists Name: ISO-8859-15 MIBenum: 111 Source: ISO Please see: http://www.iana.org/assignments/charset-reg/ISO-8859-15 Alias: ISO_8859-15 Alias: Latin-9 so the official alias is Latin-9, not latin9. You may want to ask the submitter of that entry why this inconsistency was introduced. Unfortunately, I got no reply and I really cannot see any reason for this inconsistency; probably it was a mistake or carelessness. According to http://recode.progiciels-bpi.ca/manual/Tabular.html, l9 and latin9 are aliases for this charset. Source: ISO 2375 registry. So I think it cannot harm adding latin9 as an alias name. Latin-9 will then be recognized automatically since I think capitalization and hyphens do not matter anyway (I'll check that). Shall I proceed writing such a patch? Shall I also add latin0 and l0 which are other inofficial aliases? -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
On 15 dic, 07:44, dyork reverse [EMAIL PROTECTED] wrote: When getting data from a database using the dbapi and an SQL query, how do you in general round trip the data? Especially date-time? An SQL datetime column translates nicely into a Python datetime (surprise), which then translates into a string like '2005-08-03 07:32:48'. No problem with that -- all works quite nicely, until you try to put data back the other way. Dont convert to string and keep the datetime object. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
[Christoph Zwerschke] And can somebody explain what is exactly meant with homogenous data? This seems to have been explained a few times recently :) Basically, if you have a list of xs and remove one item from it, it is still a list of xs, where xs might be people, coordinate-pairs, numbers or whatever made sense to you. If you have a tuple containing, say, a 2d coordinate pair, and remove something from it, it's no longer a coordinate pair. If you add one to it, it's something else as well (perhaps a 3d coord?) A typical example of their combined use is a set of rows returned from a database: each row is a tuple of fields, the same as all other such rows, and removing or adding a field would make no sense. However, add a new row to the list and it remains a list of rows. Now you can take this or leave it within Python. You can but mixed values into a list so it isn't really a list of xs unless x is just thing. Likewise you can use a tuple to hold a list of identical things although you can't add to it or take away. Concretely speaking, which data type should I use for coordinate tuples? Usually, tuples are used. Does this mean that I should better use lists from now on because all the components have the same type? This would seem to be slightly false logic (and very possibly used tongue-in-cheek). Heterogeneous data doesn't mean that each item *has* to be different, merely that they *may* be. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: skip last line in loops
James Stroud wrote: See the documentation for xreadlines. why? /F -- http://mail.python.org/mailman/listinfo/python-list
sEcOnD LIfe; Be wHaT eVeR u wAnt To bE!!!!
Second Life is a 3-D virtual world entirely built and owned by its residents. Since opening to the public in 2003, it has grown explosively and today is inhabited by a total of 2,007,546 people from around the globe. YOU LIVE IN A VIRTUAL WORLD, WHERE YOU CHOOSE HOW YOU LOOK AND WHAT YOU WANT TO DO IN LIFE well its in developing stage and will require all the talent and potential , so if you think you can do something really different this is the place you really want to be!!! From the moment you enter the World you'll discover a vast digital continent, teeming with people, entertainment, experiences and opportunity. Once you've explored a bit, perhaps you'll find a perfect parcel of land to build your house or business. You'll also be surrounded by the Creations of your fellow residents. Because residents retain the rights to their digital creations, they can buy, sell and trade with other residents. The Marketplace currently supports millions of US dollars in monthly transactions. This commerce is handled with the in-world currency, the Linden dollar, which can be converted to US dollars at several thriving online currency exchanges. http://www.secondlife.com/?u=8731f5b8b5b14d8611be48107c7b72b1 (MIGHTY ALEXANDRE) HOPE TO SEE YOU IN MY WORLD -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
On 14 Dec 2006 06:24:38 -0800, Glenn Hutchings [EMAIL PROTECTED] wrote: What I'm saying is that from the perspective of someone not interested in design issues, it seems like an omission for tuples to be missing the non-modifying methods that lists have. From the perpective of somone not interested in Football, the offside rule looks very strange - but I'm not making any suggestions as to how it should be changed. -- Cheers, Simon B [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Problem comparing object graphs and trees
Dear all, I am trying to compare graphes of object through the use of the __cmp__ operator. Before managing the problem of recursive comparison, I have tried a simple test which result surprises me. Here is the simplest code I can write that presents my problem: /pre $ cat cmp.py class A: def __init__(self, b): self.b = b def __cmp__(self, other): return self.b == other.b class B: pass if __name__ == '__main__': b = B() a1 = A(b) a2 = A(b) print a1 == a2 print a1 == a1 $ python cmp.py False False /pre I swear I am not drunk, but why isn't a1 == a2 and worse why isn't a1 == a1? Does someone have a clue and can explain to me this suprising behavior? (python 2.4.3 on Ubuntu 6.06). Cheers, r. -- http://mail.python.org/mailman/listinfo/python-list
Re: skip last line in loops
[EMAIL PROTECTED] writes: for line in open(file): print line. I want to skip printing last line of the file.thanks def all_but_last(it): # yield all but last item of an iterator a = it.next() for b in it: yield a a = b for line in all_but_last(open(file)): print line -- http://mail.python.org/mailman/listinfo/python-list
Re: AI library
On 15 dic, 08:50, Felix Benner [EMAIL PROTECTED] wrote: I thought about an AI library for python. This is the possible structure I came up with. Are there any thoughts about it? Without commenting about the library itself: None, True and False are spelled this way. None is a singleton, compare using x is None or x is not None, dont use == This is more stylish, but I prefer to use isxxx() or hasxxx() for functions that return booleans. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Large files uploading
Fredrik, Thank you for your reply I need to upload large files ( about 100MB ). HTTP protocol provides FORMs for uploading which is elegant and good solution for small files but using HTTP protocol for large files is not good ( server's timeouts, big memory consumption on server's side, etc.). So,I was thinking about FTP protocol, but there may be better solutions too. (FTP server would be running on server) I am sure, it can be done this or that way in Python too. (YouTube.com is a good example) Do you have any idea how to do that? Thank you Lad, As I mentioned YouTube also uses Python , so I thi But how to call the FTP API from Python? if you want the users to upload things using FTP, why do *you* need to call the FTP API (whatever that is) from Python ? why not just set up a server? -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem comparing object graphs and trees
[EMAIL PROTECTED] wrote: /pre $ cat cmp.py class A: def __init__(self, b): self.b = b def __cmp__(self, other): return self.b == other.b class B: pass if __name__ == '__main__': b = B() a1 = A(b) a2 = A(b) print a1 == a2 print a1 == a1 $ python cmp.py False False /pre I swear I am not drunk, but why isn't a1 == a2 and worse why isn't a1 == a1? Does someone have a clue and can explain to me this suprising behavior? (python 2.4.3 on Ubuntu 6.06). __cmp__() must return 0 for equal objects: 1 .__cmp__(0), 1 .__cmp__(1), 1 .__cmp__(2) (1, 0, -1) You might have a look at rich comparison before you proceed: class A(object): ... def __init__(self, b): ... self.b = b ... def __eq__(self, other): ... return self.b == other.b ... A(1) == A(1) True A(1) == A(42) False Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem comparing object graphs and trees
I am not drunk but should have rtfm. Sorry and Thanks. r. On Dec 15, 3:04 pm, Peter Otten [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: /pre $ cat cmp.py class A: def __init__(self, b): self.b = b def __cmp__(self, other): return self.b == other.b class B: pass if __name__ == '__main__': b = B() a1 = A(b) a2 = A(b) print a1 == a2 print a1 == a1 $ python cmp.py False False /pre I swear I am not drunk, but why isn't a1 == a2 and worse why isn't a1 == a1? Does someone have a clue and can explain to me this suprising behavior? (python 2.4.3 on Ubuntu 6.06).__cmp__() must return 0 for equal objects: 1 .__cmp__(0), 1 .__cmp__(1), 1 .__cmp__(2)(1, 0, -1) You might have a look at rich comparison before you proceed: class A(object):... def __init__(self, b): ... self.b = b ... def __eq__(self, other): ... return self.b == other.b ... A(1) == A(1) True A(1) == A(42)False Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem comparing object graphs and trees
[EMAIL PROTECTED] wrote: I swear I am not drunk, but why isn't a1 == a2 and worse why isn't a1 == a1? Does someone have a clue and can explain to me this suprising behavior? (python 2.4.3 on Ubuntu 6.06). Because the __cmp__ method doesn't return a boolean. It returns a value 0, 0 or 0 according to the relative ordering of its arguments. You are returning True (1) when the values are equal and you should be returning 0. If ordering isn't defined for your objects then define __eq__ instead of __cmp__. -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
greg schrieb: Ken Tilton wrote: The reason I post macro expansions along with examples of the macro being applied is so that one can see what code would have to be written if I did not have the defskill macro to write them for me. It seems to me your brain is somewhat stuck on the use of macros. That you see it this way is normal. A BASIC programmer would tell you the same thing. He can show you solutions that don't use classes, methods or functions. Some sweet gotos and gosubs are enough. The idea is that macros save you tokens and allow you to experess in a clearer way what you want to do. But in no case one needs them to solve a programming problem. All what Kenny showed could be done without his macro. It would just be a bit more complicated and the resulting code wouldn't look good. You're looking at the expansion of your macro and assuming that you'd have to write all that code by hand if you didn't have macros. You're not thinking about alternative approaches, which could just as well be used in Lisp as well as Python, that are just as compact yet don't make use of macros. He wouldn't have to write the full expansion. With functional programming he could also solve it, but then he would need a funcall here, a lambda there. And his code would not look so understandable anymore, because it is filled up with some low level details. I will take one of the first macro examples form On Lisp. Let's say for some reason you want to analyse some numbers and do something depending on their sign. We want a function numeric if: def nif(num, pos, zero, neg): if num 0: return pos else: if num == 0: return zero else: return neg In Lisp very similar: (defun nif (num pos zero neg) (case (truncate (signum num)) (1 pos) (0 zero) (-1 neg))) Now one example Graham gives is: (mapcar #'(lambda (x) (nif x 'p 'z 'n)) '(0 2.5 -8)) which results in the list (Z P N). You can do the same thing in Python. But it gets hairier if we want to make function calls that have side effects. Let me add these three functions: (defun p () (print very positive) positive) (defun z () (print no no) zero) (defun n () (print very negative) negative) And now see what happens: CL-USER (mapcar #'(lambda (x) (nif x (p) (z) (n))) '(0 2.5 -8)) very positive no no very negative very positive no no very negative very positive no no very negative (zero positive negative) The messages were printed in each case. To stop that I need lazy evaluation: CL-USER (mapcar #'(lambda (x) (funcall (nif x #'(lambda () (p)) #'(lambda () (z)) #'(lambda () (n) '(0 2.5 -8)) no no very positive very negative (zero positive negative) I put the calls to the functions p, z and n into a function object. In some languages it would look a bit cleaner, for example Ruby. They have a single name space and don't need funcall and lambda is shorter. But still, we need to add several tokens. Maybe Haskell has built in support for that. Now with nif as a macro: (defmacro nif (expr pos zero neg) `(case (truncate (signum ,expr)) (1 ,pos) (0 ,zero) (-1 ,neg))) It is a bit more complex as the function. It has one ` and 4 ,s extra. But now we can express the problem very well: CL-USER (mapcar #'(lambda (x) (nif x (p) (z) (n))) '(0 2.5 -8)) no no very positive very negative (zero positive negative) And the first example also still works the same way. Now the expansion shows more code than we would have need to write ourself. However, now we can write code that matches much better how we think. No need for low level details like embedding the code inside of anon functions. This represents what most macros do. Save one or more lambdas and/or funcalls. One consequence is that development time gets cut down. André -- -- http://mail.python.org/mailman/listinfo/python-list
Restrictive APIs for Python
Python has no inherent provision for a restrictive API that blocks accesses to methods and variables outside an allowed set. Inexperienced Python programmers may fail to adhere to an agreed-upon API, directly accessing the private internals of a class. Adherence to defined APIs is a good thing. This function allows a class to specify its API, and raise AttributeErrors for disallowed accesses. def restrictiveApi(klas): class newklas: def __init__(self, *args): self.__inst = apply(klas, args) def __getattr__(self, attr): # If the attribute is in the permitted API, then return # the correct thing, no matter who asks for it. # if attr in self.__inst._PUBLIC: return getattr(self.__inst, attr) # If the attribute is outside the permitted API, then # return it only if the calling class is in the list of # friends. Otherwise raise an AttributeError. # elif hasattr(self.__inst, '_FRIENDS'): # find the class of the method that called us try: raise Exception except: import sys tb = sys.exc_info()[2] callerClass = tb.tb_frame.f_back.\ f_locals['self'].__class__ # if it's a friend class, return the requested thing if callerClass.__name__ in self.__inst._FRIENDS: return getattr(self.__inst, attr) # if not a friend, raise an AttributeError raise AttributeError, attr return newklas To use this, a class needs to define two class variables, _PUBLIC and _FRIENDS, both being lists (or tuples) of strings. The _PUBLIC list gives the names of all methods and variables that should be considered public, i.e. any other class may use them. The _FRIENDS list gives the names of classes that are allowed free access to all methods and variables in the protected class. The _FRIENDS list is optional. Having defined _PUBLIC and optionally _FRIENDS, use something like the following to protect your class. Restricting the API will incur a performance overhead, so it's best to do it under the control of some sort of debug flag. if debug_flag: from restrictive import restrictiveApi MyClass = restrictiveApi(MyClass) Examples == class ClassUnderTest: # This class has a private variable called privateX. It can be # set using the setX() method or gotten using the x() method. # If another class appears in the _FRIENDS list, that class # can access privateX directly. # _PUBLIC = ('x', 'setX') _FRIENDS = ('FriendClass',) def __init__(self, x): # __init__ is always callable by anybody self.setX(x) def x(self): # callable by anybody return self.privateX def setX(self, x): # callable by anybody self.privateX = x ClassUnderTest = restrictiveApi(ClassUnderTest) class FriendClass: def getX(self, cut): return cut.privateX # this works fine class StrangerClass: def getX(self, cut): return cut.privateX # this raises an AttributeError -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
greg wrote: Ken Tilton wrote: So this: (defmethod tf-reverse (id (eql ',sub-id)) resx (drv-opnds tf drv)) ,@reverser) becomes this: (defmethod tf-reverse ((id (eql ',sub-id)) tf drv aux (opnds (drv-opnds tf drv))) (loop for resx in (results drv) ,@reverser)) I don't see why you can't just write a function that loops over the results and calls the user's reversal function for each one. That was the original coding, but notice that a derivation (DRV) is an argument to tf-reverse. Can you say encapsulation? :) What if that changes? It did. I used to have just one result per derivation, until a multi-result case came along. Since I will be having many dozens of these I might well try to keep as much code as possible out of them (encapsulation de damned g) to minimize the inevitable hit when I refactor, but I have macros so I do not have to. def reverse_multiple(skill, resx_list, opnds): for resx in rex_list: skill.reverse(resx, opnds) There's no need to macro-expand this code into every reversal function, when it can be done once as part of the framework that calls the reversal functions. Rather than go into argue mode before fully understanding the issues, please note that I am just looking to learn (without judgment) what the Python equivalent would be. Things I offer are not you can't touch this!, they are what does the Python look like?. Afterwards we can get into a pissing match. :) ken -- Algebra: http://www.tilton-technology.com/LispNycAlgebra1.htm Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it. -- Elwood P. Dowd I'll say I'm losing my grip, and it feels terrific. -- Smiling husband to scowling wife, New Yorker cartoon -- http://mail.python.org/mailman/listinfo/python-list
Re: skip last line in loops
On 14 Dec 2006 22:47:23 -0800, [EMAIL PROTECTED] wrote: hi, how can i skip printing the last line using loops (for /while) eg for line in open(file): print line. I want to skip printing last line of the file.thanks while True: line1 = myfile.readline() if not line1: break line2 = myfile.readline() if line2: print line1 else: break Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
greg wrote: Ken Tilton wrote: The reason I post macro expansions along with examples of the macro being applied is so that one can see what code would have to be written if I did not have the defskill macro to write them for me. It seems to me your brain is somewhat stuck on the use of macros. You're looking at the expansion of your macro and assuming that you'd have to write all that code by hand if you didn't have macros. You're not thinking about alternative approaches,... I think your brain is stuck on flaming. I am not thinking about Python approaches, I am sking Pythonistas to do that. After understanding my examples. Unfortunately I do not see the latter really happening, so we are about done here. Unless there's something very subtle that I'm missing (I can't claim to follow exactly what all the code you posted does in detail) I haven't seen anything that couldn't be done quite reasonably with an appropriate data structure and ordinary functions and methods operating on that data structure. I did explain the last little fun bit (where reverse code miraculously got a case-specific signed-value parameter bound to exactly the right bit of math structure). This process works only if you then ask specifically about that (if anything was unclear--my guess is you did not try all that hard since you are in argue-mode). The other reason you may not have understodd is that that is way meta-cool, so meta I do understand if it went over your head and I would (have been) happy to explain had you asked. Time to put the game on, I think. :) ken -- Algebra: http://www.tilton-technology.com/LispNycAlgebra1.htm Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it. -- Elwood P. Dowd I'll say I'm losing my grip, and it feels terrific. -- Smiling husband to scowling wife, New Yorker cartoon -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
André Thieme [EMAIL PROTECTED] writes: def nif(num, pos, zero, neg): if num 0: return pos else: if num == 0: return zero else: return neg def nif(num, pos, zero, neg): return (neg, zero, pos)[cmp(num, 0)+1] The messages were printed in each case. To stop that I need lazy evaluation: CL-USER (mapcar #'(lambda (x) (funcall (nif x #'(lambda () (p)) #'(lambda () (z)) #'(lambda () (n) '(0 2.5 -8)) in Python: def lazy_nif(num, pos, zero, neg): return (neg, zero, pos)[cmp(num, 0)+1]() # the () at the end means funcall map(lambda x: lazy_nif(x, p, z, n), (0, 2.5, -8)) nif is even cleaner in Haskell, if I have this right: nif x p z n | (x 0) = n | (x == 0) = z | (x 0) = p All Haskell evaluation is automatically lazy, so no lambdas etc. needed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing __length_hint__ in __getitem__ iterator
Peter Otten wrote: It's there, just not doctored into the dir() output: class A(object): ... def __getitem__(self, index): return index ... def __len__(self): return 42 ... iter(A()).__length_hint__ built-in method __length_hint__ of iterator object at 0x401d558c iter(A()).__length_hint__() 42 Peter Ah well, actually it's there also in dir(), you just need to use Python 2.5 of course ;) -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
re pattern for matching JS/CSS
I'm working on a program to remove tags from a HTML document, leaving just the content, but I want to do it simply. I've finished a system to remove simple tags, but I want all CSS and JS to be removed. What re pattern could I use to do that? I've tried 'script[\S\s]*/script' but that didn't work properly. I'm fairly basic in my knowledge of Python, so I'm still trying to learn re. What pattern would work? -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Paul Rubin wrote: André Thieme [EMAIL PROTECTED] writes: def nif(num, pos, zero, neg): if num 0: return pos else: if num == 0: return zero else: return neg def nif(num, pos, zero, neg): return (neg, zero, pos)[cmp(num, 0)+1] Since we are in one liners, let's be even smarter and do it like that : def nif(num, pos, zero, neg): return (zero, pos, neg)[cmp(num, 0)] ;) -- http://mail.python.org/mailman/listinfo/python-list
parsing a dictionary from a string
Hello list, I could use some help extracting the keys/values of a list of dictionaries from a string that is just the str() representation of the list (the problem is related to some flat file format I'm using for file IO). Example: s = str(dict_list) s '[{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}]' Then, what I want to do is to reconstruct dict_list given s. Now, one possible solution would be dict_list = eval(s) but since the content of s cannot be blindly trusted I`d rather not do it that way. Basically my question is whether there is another solution which is simpler than using regular expressions. Best, Benjamin -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
Tim Golden wrote: Christoph Zwerschke wrote: And can somebody explain what is exactly meant with homogenous data? This seems to have been explained a few times recently :) Basically, if you have a list of xs and remove one item from it, it is still a list of xs, According to that definition, everything would be homogenous. I guess what you wanted to say is if you have an x and remove one item from it it is still an x, then it's homogenous. The problem is that depending on how exactly you define x, you will come to different results. If you have a tuple containing, say, a 2d coordinate pair, and remove something from it, it's no longer a coordinate pair. Now here comes the ambiguity. If you interpret x as coordinate tuple it would be still one (a 1-tuple), but if you interpret x as coordinate pair then it would indeed not be an x any more. So that definition is not really helpful. A typical example of their combined use is a set of rows returned from a database: each row is a tuple of fields, the same as all other such rows, and removing or adding a field would make no sense. However, add a new row to the list and it remains a list of rows. Sounds plausible. But when I read a row with the name and forename of a person, I might want to collapse the name and forename into one element before I hand it over to a function that will display it as a table. Or I may want to delete certain elements which are not important. In such cases, having each row as list may also make sense. Concretely speaking, which data type should I use for coordinate tuples? Usually, tuples are used. Does this mean that I should better use lists from now on because all the components have the same type? This would seem to be slightly false logic (and very possibly used tongue-in-cheek). Heterogeneous data doesn't mean that each item *has* to be different, merely that they *may* be. I don't think it's a problem of false logic but the problem that homogenous data is not defined. We probably agree that it usually makes perfect sense to use tuples for coordinates. But in certain mathematical algorithms it also makes sense to ask for the number of zero components of a coordinate tuple - the count() method would be helpful here. The statement if you are looking for index() or count() for your tuples, you're using the wrong container type is too extreme I think. I would agree with it *may indicate* that you should better use lists. -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: cxfrozen linux binaries run on FreeBSD?
I haven't personally used freeze (Kubuntu doesn't seem to install it with the python debs), but based on what I know of it, it makes make files. I'm not a make expert, but if FreeBSD has GNU tools, freeze's output _should_ be able to be compiled on FreeBSD. On Dec 15, 5:52 am, robert [EMAIL PROTECTED] wrote: When i freeze a python app (simple - no strange sys calls) for x86 Linux, does this stuff run well also on x86 FreeBSD? Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: AI library
Felix Benner wrote: [...] def a-star(self, nodeFrom, nodeTo): searches the shortest path (minimal weight) from nodeFrom to nodeTo. pass def a-star(self, nodeFrom, nodeTo): File stdin, line 1 def a-star(self, nodeFrom, nodeTo): ^ SyntaxError: invalid syntax -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
greg wrote: Ken Tilton wrote: The last example showed the macro inserting code to magically produce a binding inside the reverse function. Are you sure? It looked to me like it was adding code *around* the reverse function, not inside it. I posted a Python function that achieves the same thing by calling the existing reverse function. You are thinking about the results iteration, where you broke encapsulation. I just reminded you of the magical signed-value binding in a reply to another post of yours. btw, when looking back at the rest of the code I was reminded I had done something even wilder (well, maybe as wild) in the transforming code itself. I say wilder in the sense of it being way cool, having a flying-without-a-net feeling, yet making coding of dozens and dozens of these transformations simpler, terser, and less buggy. Someone had me laughing when they said the actual application of a macro was nice and simple, but the macro itself was scary. It reminded me of a cranky but sweet old guy on a project who was outraged upon learning I was using a finite state machine to handle a shaky exchange between two processes. He maintained that I was foisting a crazy scheme on the bank which no one would be able to maintain. He actually forced me to defend it in a group code review, the first they ever had, so don't think it was a normal process for them, this was war. After my demonstration on how the FSM would react to either or both processes going south at any point in the exchange, the crank pronounced his satisfaction with the approach and said, OK, that is simple. The infinite-state thing is complicated, but the way it works is simple. That really made the whole thing worthwhile. :) I'm still trying, but some of the code you posted is rather impenetrable without knowing a lot more about the details of your system. I'm doing my best to show some Python demonstrating the gist of what could be done. Great. That's the spirit. But how do we move forward if you just express global confusion? See if you can understand the magical binding of the parameter signed-value. The reverse function will be called by the engine to reverse a mathematical transformation, in this case simply taking the absolute value. The generic engine has no way of knowing out of all the targets, results, and operands (targets from a before expression relocated in their incarnation in the expression operated on) recorded by a transformation to pass in that position. When I code that reverse function, I just want to work on the signed-value, as identified in hard-code fashion by the transformation. ie, All I need do is coordiate the TF and its reverser. If the reverser needs something else, say the coefficient (this would be a add-like-terms TF), I just go to the add-like-terms and have it tag the coefficients with the symbol 'coefficient, then I can code: (reverse (coefficient literal-part)...) Ah. Time to refactor. I will have multiple coefficients, and when multiples are expected I want all the input math forms searched for those tagged coefficient. Any ideas out there? :) It is so tempting to add an s and have the macroexpansion look for a trailing s in the symbol-name, but then I am bound to have some singular and in s. Ah, grep to the rescue: (reverse (literal-part coefficient+)...) Sweet. By using + I can even have the macroexpansion insert an assertion that there is at least one. Of course there should be at least two or this TF would not fire. And so it goes... :) ken -- Algebra: http://www.tilton-technology.com/LispNycAlgebra1.htm Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it. -- Elwood P. Dowd I'll say I'm losing my grip, and it feels terrific. -- Smiling husband to scowling wife, New Yorker cartoon -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Christophe Cavalaria [EMAIL PROTECTED] writes: def nif(num, pos, zero, neg): return (zero, pos, neg)[cmp(num, 0)] Owwoo!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Paul Rubin wrote: nif is even cleaner in Haskell, if I have this right: nif x p z n | (x 0) = n | (x == 0) = z | (x 0) = p All Haskell evaluation is automatically lazy, so no lambdas etc. needed. You can use that style in CL. (defun nif (x p z n) (or (when ( x 0) n) (when (= x 0) z) (when ( x 0) p))) Wade -- http://mail.python.org/mailman/listinfo/python-list
Re: aggdraw for 2.5 on WinXP?
rzed a écrit : Has anyone generated an aggdraw installer or aggdraw.pyd for Python 2.5 (WinXP)? If so, could it be made available for those of us who don't have a working compiler? Hello, You can try http://c.python.free.fr/aggdraw-1.2a3-20060212.win32-py2.5.exe without any express or implied warranty. Stephane. -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Paul Rubin schrieb: André Thieme [EMAIL PROTECTED] writes: def nif(num, pos, zero, neg): if num 0: return pos else: if num == 0: return zero else: return neg def nif(num, pos, zero, neg): return (neg, zero, pos)[cmp(num, 0)+1] That is a nice idea. I can do the same in Lisp, but have to do it without syntactic sugar which makes it longer, characterwise: (defun nif2 (num pos zero neg) (nth (1+ (truncate (signum num))) (list pos zero neg))) What Python has is cmp. That is doing what truncate+signum do in Lisp. So that makes the biggest difference. Another one is that Lisps signum keeps the datatype: cmp(5.3, 0) = 1 (signum 5.3) = 1.0 Or also with complex numbers [syntax #C(real, img)]: (signum #C(10 4)) = #C(0.9284767 0.37139067) Anyway, from the complexity the Lisp version is a bit better. The Python version has 11 tokens: return, tuple-reference, comma, neg, zero, pos, +, 1, cmp, num, 0 and the Lisp version has only 9: nth, 1+, truncate, signum, num, list, pos, zero, neg (I didn't count the function head, because both have the same token count). The messages were printed in each case. To stop that I need lazy evaluation: CL-USER (mapcar #'(lambda (x) (funcall (nif x #'(lambda () (p)) #'(lambda () (z)) #'(lambda () (n) '(0 2.5 -8)) in Python: def lazy_nif(num, pos, zero, neg): return (neg, zero, pos)[cmp(num, 0)+1]() # the () at the end means funcall map(lambda x: lazy_nif(x, p, z, n), (0, 2.5, -8)) We could do the same in Lisp: (defun lazy-nif (num pos zero neg) (funcall (nth (1+ (truncate (signum num))) (list pos zero neg Here the token count is 12py vs 10cl. CL-USER (mapcar #'(lambda (x) (lazy-nif2 x #'p #'z #'n)) '(0 2.5 -8)) no no very negative very positive (zero negative positive) But there is a disadvantage: lazy_nif(0, p, z, n) Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 2, in lazy_nif TypeError: 'str' object is not callable I don't know how I can fix that. Maybe you could tell me. In Lisp I would just go with the macro. That works for all cases. nif is even cleaner in Haskell, if I have this right: nif x p z n | (x 0) = n | (x == 0) = z | (x 0) = p All Haskell evaluation is automatically lazy, so no lambdas etc. needed. Yes, that was what I already supposed. Do you also know how I can deactivate lazyness? André -- -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
On 12/15/06, Christoph Zwerschke [EMAIL PROTECTED] wrote: Maybe there would be less dispute if this dogma/convention(?) Tuples are for heterogeneous data, list are for homogeneous data would be written down somewhere in the tutorial, reference or in PEP8, so people would be aware of it. It's not a dogma. It's just that it explains the intention behind the designs of the tuple and list APIs. If you use them for thier intended purposes, naturally you'll find the APIs more helpful. But you won't find the data-structure police breaking down your doors in the small hours if you choose to go your own way[1]. I can use a spreadsheet to write a letter if I want to - but it would be foolish to complain that the word wrapping was a bit dodgy. -- Cheers, Simon B [EMAIL PROTECTED] [1] The PSU, on the other hand, [EMAIL PROTECTED]( -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Christophe Cavalaria schrieb: Paul Rubin wrote: André Thieme [EMAIL PROTECTED] writes: def nif(num, pos, zero, neg): if num 0: return pos else: if num == 0: return zero else: return neg def nif(num, pos, zero, neg): return (neg, zero, pos)[cmp(num, 0)+1] Since we are in one liners, let's be even smarter and do it like that : def nif(num, pos, zero, neg): return (zero, pos, neg)[cmp(num, 0)] Okay, that reduces the complexity of the Python version to that of Lisp. Now both have the same token count. André -- -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Wade Humeniuk [EMAIL PROTECTED] writes: nif is even cleaner in Haskell, if I have this right: nif x p z n | (x 0) = n | (x == 0) = z | (x 0) = p All Haskell evaluation is automatically lazy, so no lambdas etc. needed. You can use that style in CL. (defun nif (x p z n) (or (when ( x 0) n) (when (= x 0) z) (when ( x 0) p))) Yeah but you can't apply it the same way. [nif x p z n | x - [0,2.5,-8]] evaluates exactly one of p, z, or n, for each of the args in that list. Side effects don't work the same way either, you have to use special declarations around code with side effects. I'm not yet conversant enough with Haskell to know how to do it for this example though. -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
André Thieme [EMAIL PROTECTED] writes: and the Lisp version has only 9: nth, 1+, truncate, signum, num, list, pos, zero, neg Oh come on, you have to count the parentheses too. Anyway, token count doesn't mean much, you have to instead go by the user's cognitive effort in dealing with the prefix notation etc., which isn't purely a matter of token count. And if (+ 2 3) were really as easy to read as 2+3, mathematics would have been written that way all along. TypeError: 'str' object is not callable I don't know how I can fix that. Maybe you could tell me. lazy_nif(0, lambda: p, lambda: z, lambda: n) All Haskell evaluation is automatically lazy, so no lambdas etc. needed. Yes, that was what I already supposed. Do you also know how I can deactivate lazyness? There's a Haskell builtin called 'seq' which forces evaluation but again I'm not sure precisely how to apply it here. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
On 12/15/06, Christoph Zwerschke [EMAIL PROTECTED] wrote: If you have a tuple containing, say, a 2d coordinate pair, and remove something from it, it's no longer a coordinate pair. Now here comes the ambiguity. If you interpret x as coordinate tuple it would be still one (a 1-tuple), but if you interpret x as coordinate pair then it would indeed not be an x any more. So that definition is not really helpful. But the new 1-tuple is no longer usable in the same contexts as the coordinate pair. In the coordinate pair, you can infer the item's meaning from its position. A typical example of their combined use is a set of rows returned from a database: each row is a tuple of fields, the same as all other such rows, and removing or adding a field would make no sense. However, add a new row to the list and it remains a list of rows. Sounds plausible. But when I read a row with the name and forename of a person, I might want to collapse the name and forename into one element before I hand it over to a function that will display it as a table. Or I may want to delete certain elements which are not important. In such cases, having each row as list may also make sense. Sure, you can translate the tuple into a different tuple for a different purpose, but in terms of the database, only the original tuple (or other with the same structure) is meaningful. The statement if you are looking for index() or count() for your tuples, you're using the wrong container type is too extreme I think. I would agree with it *may indicate* that you should better use lists. Oh, absolutely, it's not a hard and fast rule. But I find that if I try to decide whether to use a tuple or a list based on lists for homogeneous collections and tuples for heterogeneous collections where position carries semantic meaning, then I end up using the type that does what I need. Homogeneous collections often need to be sorted or searched, wheras heterogeneous collections are often used as dictionary keys. -- Cheers, Simon B [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Paul Rubin http://[EMAIL PROTECTED] writes: André Thieme [EMAIL PROTECTED] writes: and the Lisp version has only 9: nth, 1+, truncate, signum, num, list, pos, zero, neg Oh come on, you have to count the parentheses too. No. Parentheses are editor commands. They don't count anymore than spaces count in Python. -- __Pascal Bourguignon__ http://www.informatimago.com/ You question the worthiness of my code? I should kill you where you stand! -- http://mail.python.org/mailman/listinfo/python-list
Re: cxfrozen linux binaries run on FreeBSD?
i80and wrote: I haven't personally used freeze (Kubuntu doesn't seem to install it with the python debs), but based on what I know of it, it makes make files. I'm not a make expert, but if FreeBSD has GNU tools, freeze's output _should_ be able to be compiled on FreeBSD. Yet do the Linux compiled cx_freeze binaries (and Python .so's) usually run directly on FreeBSD without a lot of trouble? I have not access to a FreeBSD setup and someone wants to know the probability :-) On Dec 15, 5:52 am, robert [EMAIL PROTECTED] wrote: When i freeze a python app (simple - no strange sys calls) for x86 Linux, does this stuff run well also on x86 FreeBSD? Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: Property error
king kikapu wrote: Your example Dennis, work as expected. I understand the mistake i have made. But when i try to fix the original code usihn @property now, it gives me the same error. So, here it is: class Person(object): _age = 0 @property def age(): def fget(self): return self._age def fset(self, value): self._age = value me = Person() me.age = 34 print me.age I am sure it is something very obvious but my skills does not (yet) enable me to figure this out,,, As others have already replied, the default property doesn't work this way. In your example, it is possible to write it in one line using lambda: class Person(object): age = property(fget=lambda self: self._age, fset=lambda self, value: setattr(self,'_age',value)) If any of fget,fset,fdel cannot be written as lambda or you'd rather write them as functions, you may use the recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698. HTH, George -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
[EMAIL PROTECTED] wrote: Ken Tilton wrote: Andrew Reilly wrote: That all looks like data. No, not reverse, the part you did not understand. I do not mean what the code was doing, I meant that it was code. Code is data is code I was hoping no one would make that mistake. :) macros are all about code is data, but code is not data in Python* so the two words code and data serve to differentiate them for Pythonistas. * Taking questions after a keynote to ILC200? where he reiterated that Python was the same as Lisp for all intents and purposes: Norvig: Yes, John? McCarthy: Is code also data in Python? Norvig: No. End of exchange. :) - even in Python: This could be tougher than I thought. skills_table = [ { title: Absolute Value, annotations: [Bleah bleah, ho hum, etc...], hints: [and so on, etc...], reverse : (lambda x: whatever(x)) That does not demonstrate that code is data, that demonstrates that a lambda is a first-class object (and, yes, Python's lambda is lame). You will know you have code as data when you can write Python code that takes apart whatever(x) and produces oh-now-I-get-it(y). As part of the language, such that Python applies your transforming code for you whenever it sees whatever. (Hell, even C has a preprocessor.) }, { title: Square Root, annotations: [Bleah bleah, ho hum, etc...], hints: [and so on, etc...], reverse : (lambda x: someother(x)) }, # etc... ] Of course those lambdas are crippled in Python (and not really necessary in this bogus example)... But that's without trying to be clever: class AbsoluteValue: title=Absolute Value annotations=[Some list, goes here] @classmethod def reverse(cls, *args): # I didn't understand what your code was doing yeah, and god forbid you should ask. :) this is the crux of the matter! Actually, it is kinda cool that you and Greg are semi-identifying the crux by saying this is the only bit I do not get, I'll skip this, move on, nothing to see here. pass defskill(AbsoluteValue) That would be a reasonable place for a pie decorator on a class, but I guess that's not allowed. Hmmm. Actually, that is the whole point, all of Python is allowed. decorators were used in PyCells, but I never got much of an idea what they did. Is there a moral equivalent of a macroexpansion for decorators so you can show the before and after? I doubt this second example would be considered Pythonic in any case... exactly what we are looking for in this cultural exchange: how would Python handle what I am doing with macros in the reverse functions? Make it as slick and programmer-friendly (cuz I may get to a hundred of these before I am done with Algebra I) as possible. When all the Pythonistas proclaim it optimal, then we compare and contrast. This, btw, is the Tilton Test for language comparison: Not measurements of programmer effort, rather examination of perfect equivalent code. PyCells vs Cells would be an amazing case, because that is some hairy functionality. Not the code. In reverse. Why not? Is, too! (ie, I am kinda looking for a specific question that conveys understanding of the use case.) Python has plenty of other flaws that I can't happily work around, and I do think Lisp is more flexible. However, I think your example is readable enough with a data driven algorithm in most any popular language. All of the data is visible to the reverse(...) method. Maybe I missed something in your example, but I think you aren't trying hard enough. :-) Precisely. I am not trying at all. I am coding between visits to Usenet. This use case just popped up and was pretty simple (at first, before I got to the reverse function) so I dropped it off. This is a wild macro, not farm-bred, deliberately crafted to embarrass macro. A real live natural comes up all the time working wouldn't want to code without it macro. I could have searched my code base to find more brutal cases, but this is short and sweet and unforced and uncontrived and wheres my thesaurus? ken -- Algebra: http://www.tilton-technology.com/LispNycAlgebra1.htm Well, I've wrestled with reality for thirty-five years, Doctor, and I'm happy to state I finally won out over it. -- Elwood P. Dowd I'll say I'm losing my grip, and it feels terrific. -- Smiling husband to scowling wife, New Yorker cartoon -- http://mail.python.org/mailman/listinfo/python-list
Re: Restrictive APIs for Python
On 15 dic, 11:31, Will Ware [EMAIL PROTECTED] wrote: Python has no inherent provision for a restrictive API that blocks accesses to methods and variables outside an allowed set. Inexperienced Python programmers may fail to adhere to an agreed-upon API, directly accessing the private internals of a class. In Python, the usual way of saying don't play with me is prepending an underscore: _private BTW, have you *ever* tested your code? -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: AI library
Gabriel Genellina: This is more stylish, but I prefer to use isxxx() or hasxxx() for functions that return booleans. Lisp-like languages allow the ending ? or !, I think Ruby allows the ending ? too (allowing it with Python may be positive). Mathematica usually uses an ending uppercase Q, like PrimeQ, sometimes I use the ending Q in Python too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
On Tue, 12 Dec 2006 09:29:17 +0100, Matias Jansson [EMAIL PROTECTED] wrote: I come from a background of Java and C# where it is common practise to have one class per file in the file/project structure. As I have understood it, it is more common practice to have many classes in a Python module/file. What is the motivation behind it, would it be a bad idea to have a guideline in your project that promotes a one class per file structure (assuming most of the programmers a background similar to mine)? Never mind their background; think about their future ;-) Besides, I think you have plenty of C and C++ hackers around, too. Seriously, I agree with what F Lundh wrote elsewhere in the thread; no need to repeat it here. /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list