Three weeks to go to Python-UK - 21-23 April, Oxford
There are just three weeks to go to Python-UK! The UK Python conference is once again taking place at the Randolph Hotel in the centre of historic Oxford, as part of the ACCU conference, on 21-23 April. http://www.accu.org/conference/python.html On Tuesday 19th there's also a full day tutorial for intermediate and advanced Python programmers, given by Michele Simionato, at a fraction of the price of most professional training courses. There are just a few places remaining, so book quickly! http://www.accu.org/conference/python_tutorial.html Anyone attending the event is free to move between tracks and learn from a world-class program on patterns, agile development, Java, C++ and C# as well as Python. Best Regards, Andy Robinson Python-UK Conference chair -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: PyDev 0.9.2 released
Hi All, PyDev - Python IDE (Python development enviroment for Eclipse) version 0.9.2 has just been released. Check the homepage (http://pydev.sourceforge.net/) for more details. Regards, Fabio Zadrozny -- Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br PyDev - Python Development Enviroment for Eclipse pydev.sf.net pydev.blogspot.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[ANN] Fail2Ban 0.3.1
The version 0.3.1 of Fail2Ban is available. Fail2Ban is written in Python. It scans log files like /var/log/pwdfail or /var/log/apache/error_log and bans IP that makes too many password failures. It updates firewall rules to reject the IP address. Currently, iptables, ipfwadm and ipfw are supported. It needs log4py. http://fail2ban.sourceforge.net Best Regards, Cyril Jaquier -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: ActivePython 2.4.1 build 245 is available
I'm pleased to announce that ActivePython 2.4.1 build 245 is now available from: http://www.ActiveState.com/Products/ActivePython ActivePython 2.4.1.245 is a bug-fix release matching the recent core Python 2.4.1 release. ActivePython builds for Linux, Solaris and Windows are available. We welcome any and all feedback to: [EMAIL PROTECTED] Please file bugs against ActivePython at: http://bugs.ActiveState.com/ActivePython What is ActivePython? - ActivePython is ActiveState's quality-assured binary build of Python. Builds for Windows, Linux and Solaris and made freely available. ActivePython includes the Python core and core extensions (zlib 1.2.1, bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.9, and Tix 8.1.4). On Windows, ActivePython includes the PyWin32 suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM, the Pythonwin IDE, and more. ActivePython also includes a wealth of Python documentation, including: - the core Python docs - Andrew Kuchling's What's New in Python series - the Non-Programmer's Tutorial for Python - Mark Pilgrim's excellent Dive into Python, and - a snapshot of the Python FAQs, HOWTOs and PEPs. An online version of the docs can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html In particular the Release Notes: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/relnotes.html and the Installation Guide: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/installnotes.html Extra Bits -- ActivePython releases also include the following packages: - a Windows debug package: debug-built binaries for ActivePython users building debug versions of their binary Python extensions - ActivePython24.chm: an MS compiled help collection of the full ActivePython documentation set. Linux users of applications such as xCHM might find this useful. This package is installed by default on Windows. These packages are available from: ftp://ftp.activestate.com/ActivePython/etc/ On behalf of the team at ActiveState, Thanks, and enjoy! -- Trent Mick [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Queue.Queue-like class without the busy-wait
Op 2005-03-31, [EMAIL PROTECTED] schreef [EMAIL PROTECTED]: Cool Code! One possible sticking point is that I think select only works on network sockets on windows. This would make the code not crossplatforn. As far as I understand, what I did with pipes, can be done just as fine with network sockets. If someone want to rewrite the code to do so and make the code more crossplatform, I'll happily incorperate it. I'm just not familiar enough with sockets to do it myself. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: (SPAM: 50) Mail Delivery (failure jobs-bangalore@google.com) (VIRUS REMOVED)
We want to thank you for your interest in joining the Google team. We received your email inquiry and look forward to the opportunity to review your background and experience. Unfortunately, we are unable to give a personal reply to every applicant. However, please know that we do review all resumes by hand so it takes us just a little bit longer to get back to applicants we feel might be a fit for one of our positions. If you do not hear from one of us, we may not have a position available for you at this time. We thank you for your patience and want to thank you again for your interest in Google. Google Staffing http://www.google.com/jobs.html -- http://mail.python.org/mailman/listinfo/python-list
Re: hex string into binary format?
Tertius Cronje [EMAIL PROTECTED] wrote: How do I get a hexvalued string to a format recognized for binary calculation? You're going to be embarrassed. import binascii s1 = '1C46BE3D9F6AA820' s2 = '8667B5236D89CD46' i1 = binascii.unhexlify(s1) i2 = binascii.unhexlify(s2) x = i1 ^i2 TypeError: unsupported operand type(s) for ^: 'str' and 'str' No imports at all: s1 = '1C46BE3D9F6AA820' s2 = '8667B5236D89CD46' i1 = int(s1,16) i2 = int(s2,16) x = i1 ^ i2 print hex(x) -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary: sorting the values preserving the order
Rakesh wrote: Hi, For a particular problem of mine, I want to sort key, value pairs by its value. Eg: Input: A, 4 B, 5 C, 1 D, 2 E, 3 I would like the output to be: C D E A B the following code does that: d1 = {'a':4,'b':5,'c':1,'d':2,'e':3} i1 = [ (d1[i], i) for i in d1.keys() ] i1.sort() i1 [(1, 'c'), (2, 'd'), (3, 'e'), (4, 'a'), (5, 'b')] for each in i1: ... print each[1] c d e a b thanks, Satchit i.e. I would like to get the keys in the sorted order of values. I did google around a little bit. One solution to a similar problem suggested is: # Courtesy: http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52306 def sortedDictValues3(adict): keys = adict.keys() keys.sort() return map(adict.get, keys) This gets a list sorted by the keys. How would I get a revised dictionary sorted by its values. -- http://mail.python.org/mailman/listinfo/python-list
Re: Our Luxurious, Rubinesque, Python 2.4
Larry Hastings wrote: Also, how much would I be able to trim away if I recompiled it myself? Is a lot of it native implementations of Python libraries that I might not care about including, or is it all fundamental VM stuff that couldn't possibly be removed? In Pythons config.c file You can determine which ext-modules will be compiled into the core. I estimate that a lean core would have a size around ~600kb. Trimming down further may become hard because You may have to decide what to sacrifice: tuples, classes or objects ;) Regards, Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: string goes away
Andreas Beyer wrote: I loved to use string.join(list_of_str, sep) instead of sep.join(list_of_str) I think the former is much more telling what is happening than the latter. However, I will get used to it. No need to get used to it. Just reverse the order of the arguments and use: str.join(sep, list_of_str) Alternatively it can be clearer if you bind a name to the bound method: joinLines = '\n'.join joinWords = ' '.join lines = joinLines(somelines) words = joinWords(somewords) -- http://mail.python.org/mailman/listinfo/python-list
Re: System bell
On Fri, 01 Apr 2005 02:06:07 -0500, Steve Holden [EMAIL PROTECTED] wrote: Trent Mick wrote: [Baza wrote] Am I right in thinking that print \a should sound the system, 'bell'? It works on the shell on Windows for me (WinXP). Trent Interesting. From a Cygwin bash shell I got an elegant little dingish sort of a beep (my volume control was set kind of low). I then ran the same code in a Windows shell and nearly deafened myself. It appears that the volume control doesn't affect the Windows XP commans shell beep - even muting the Windows audio output doesn't stop it (though it does stop the Cygwin beep). This could cause heart attacks! Another couple of data points: Running python 2.3/MSVC6 or python 2.4/MinGW in an NT4 console window, print '\a' beeps via the PC internal speaker (like winsound.Beep). Running the bash shell of msys, echo -e '\a' also beeps via the PC speaker. These are not affected by any volume control that I know of. But running py2.3 idle, print '\a' displays a square empty box (which I take to be the symbol for unprintable characters). That seems like an oversight in terminal emulation. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib problem (maybe bugs?)
Timothy Wu [EMAIL PROTECTED] wrote: I'm trying to fill the form on page http://www.cbs.dtu.dk/services/TMHMM/ using urllib. There are two peculiarities. First of all, I am filling in incorrect key/value pairs in the parameters on purpose because that's the only way I can get it to work.. For version I am suppose to leave it unchecked, having value of empty string. And for name outform I am suppose to assign it a value of -short. Instead, I left out outform all together and fill in -short for version. I discovered the method my accident. After I've done that it works fine for small SEQ values. Then, when I try to send large amount of data (1.4MB), it fails miserably with AttributeError exception. I highly suspect the two problems I have are the result of some bugs in the urllib module. Any suggestions? The form on that page wants multipart/form-data encoding, where each parameter is embedded in a separate MIME section. That is common with very large data, and is _required_ when the form includes a file upload. urllib doesn't do that. It always sends plain old application/x-www-form-urlencoded data. I think you're going to have to roll your own sender. -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
that is it is not it (logic in Python)
I want to know if iter(iterator) returns always its argument (when argument is an iterator) So : iterable = range(10) it = iter(iterable) that = iter(it) that is it True# Good! that is it is not it False # What ? Python = map(bool, it) logic = True logic in Python is not it True # That was close! that is it or it is not it True # from physics.constant import N N = 6.02e+27 big = 192 # cm 1.92 meter is big for me (see my name) N is big False # what ? -- Seriously on an April fool's day. -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary: sorting the values preserving the order
On 31 Mar 2005 22:40:53 -0800, Rakesh [EMAIL PROTECTED] wrote: Hi, For a particular problem of mine, I want to sort key, value pairs by its value. Eg: Input: A, 4 B, 5 C, 1 D, 2 E, 3 I would like the output to be: C D E A B i.e. I would like to get the keys in the sorted order of values. Generally, dictionaries nearly always have two parts. The dictionary itself, and a separate list of keys to access it with. To access the dictionary in a particular order, you just need a sorted key list. Since what you want is to access by value, you need to create a second dictionary with the values as the keys. That will only work if the values never repeat. If they do, then you need to use a list and not a dictionary. This creates a second dictionary with a sorted value key list. alpha_dict = {'A':4, 'B':5, 'C':1, 'D':2, 'E':3} # Create a new dictionary with keys and values exchanged. num_dict = {} for k in alpha_dict.keys(): num_dict[ alpha_dict[k] ] = k # Get the num_dict keys and sort them. num_keys = num_dict.keys() num_keys.sort() Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ method and raising exceptions
I can't use 'break' or 'continue' in a class method, nor can I return a boolean value from __init__() to check for errors within the for-loop. How would I be able to stop the current iteration and continue with the next after reporting an error? maybe i don't fully understand your qn but why don't you let __init__ of your class raise an exception and then catch it in the outer for loop and continue. something like: for i in ... try: foo() except: continue Vikram -- http://mail.python.org/mailman/listinfo/python-list
Re: split an iteration
Robin Becker wrote: eg for e = enumerate([0,1,2,3,4,5]) for i,a in e: ... if a==3: break ... for i,a in e: ... print i,a ... 4 4 5 5 I think the second loop needs to start at 3 ie the split needs to be start, limit semantics It would be nice to be able to fix it with a move back method. I have to reread your previous post, it seems. Meanwhile: e = enumerate(range(6)) for i, a in e: ... if a == 3: ... for i, a in itertools.chain([(i, a)], e): ... print i, a ... break ... 3 3 4 4 5 5 Nesting the loops is necessary to handle empty lists and lists with no matching item correctly. Alternatively, you could set a 'found' flag. Another option: def predicate((i, a)): return a != 3 ... for i, a in itertools.dropwhile(predicate, enumerate(range(6))): ... print i, a ... 3 3 4 4 5 5 The extra function call might have a negative impact on performance, though. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
You could use condition and consequent or alternative I use it Sean On Apr 1, 2005 5:24 PM, praba kar [EMAIL PROTECTED] wrote: Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this __ Yahoo! Messenger Show us what our next emoticon should look like. Join the fun. http://www.advision.webevents.yahoo.com/emoticontest -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Pre-PEP: Dictionary accumulator methods
Greg Ewing wrote: Steven Bethard wrote: py def defaultdict(*args, **kwargs): ... defaultfactory, args = args[0], args[1:] which can be written more succinctly as def defaultdict(defaultfactory, *args, **kwargs): ... Not if you want to allow the defaultfactory to be called with a keyword argument 'defaultfactory'. Compare my code: py def defaultdict(*args, **kwargs): ... defaultfactory, args = args[0], args[1:] ... print defaultfactory, args, kwargs ... py defaultdict(dict, defaultfactory=True) type 'dict' () {'defaultfactory': True} with the code you suggested: py def defaultdict(defaultfactory, *args, **kwargs): ... print defaultfactory, args, kwargs ... py defaultdict(dict, defaultfactory=True) Traceback (most recent call last): File interactive input, line 1, in ? TypeError: defaultdict() got multiple values for keyword argument 'defaultfactory' Uncommon, sure, but I'd rather not rule it out if there's no need to. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: property and virtuality
Hello, I asked this question some time ago, but as I got no answer, so I just try it a second time. I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = foobar How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? Thanks for your help, - harold - -- Always remember that you are unique; just like everyone else. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: New to programming question
On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney [EMAIL PROTECTED] wrote: Oh goddammmni. I seem to be doing this a lot today. Look below for the extra addition to the code I posted. Joal Heagney wrote: Here's my contribution anycase: count = 0 # Get first input name = raw_input(Guess my name: ) # Give the sucker two extra goes while count 2: # Check the value of name if name == 'Ben': print You're right! break else: name = raw_input(Try again: ) # Here's the bit I missed out. count += 1 # Of course, we haven't checked the sucker's last guess # so we have to do that now. if count == 2: if name == 'Ben': print You're right! else: print No more tries for you!!! Hope this helps. Joal G. Need something more straightforward, e.g., a wrapped one-liner: def guess(n=3): print (You're right!, 'No more tries for you!!!')[n-1 in ...(x for x in xrange(n) for t in [raw_input('Guess my name: ')=='Ben'] ...if not t or iter([]).next())] ... guess() Guess my name: Jack Guess my name: Bob Guess my name: Ben You're right! guess() Guess my name: Jack Guess my name: Ben You're right! guess() Guess my name: Kermit Guess my name: Ms Piggy Guess my name: Ernie No more tries for you!!! guess(1) Guess my name: Einstein No more tries for you!!! guess() Guess my name: Ben You're right! Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
praba kar wrote: Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. http://www.python.org/peps/pep-0308.html -- http://mail.python.org/mailman/listinfo/python-list
StopIteration in the if clause of a generator expression
To confuse a newbies and old hands alike, Bengt Richter wrote: Need something more straightforward, e.g., a wrapped one-liner: def guess(n=3): print (You're right!, 'No more tries for you!!!')[n-1 in ...(x for x in xrange(n) for t in [raw_input('Guess my name: ')=='Ben'] ...if not t or iter([]).next())] ... guess() To make it a bit clearer, a StopIteration raised in a generator expression silently terminates that generator: def stop(): raise StopIteration ... list(i for i in range(10) if i 5 or stop()) [0, 1, 2, 3, 4] In a list comprehension, on the other hand, it is propagated: [i for i in range(10) if i 5 or stop()] Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 1, in stop StopIteration Is that an intentional difference? Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
Sean Kemplay wrote: You could use condition and consequent or alternative I use it You should do so cautiously, since if consequent is false, it will not behave as suspected. Not to mention that it's quite unreadable. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis Physics, as we know it, will be over in six months. -- Max Born (1928) -- http://mail.python.org/mailman/listinfo/python-list
class attributes and inner classes in C extensions
Hello, I just posted this question with a wrong subject... So here again with a better one. I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = foobar How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? Thanks for your help, - harold - -- Always remember that you are unique; just like everyone else. -- -- http://mail.python.org/mailman/listinfo/python-list
A ClientForm Question
Does anyone here use ClientForm to handle a HTML form on client side? I got a form, within which there is a image control, it direct me to another page if i use mouse click on it. the code of the form as below: form name=ZoomControl1:Form1 method=post action=CDocZ_MAG.aspx?Stat=DocZoom_DocZoomamp;amp;E=29YL53ZJBIEZamp;DT=ALBamp;Pass=amp;Total=104amp;Pic=1amp;o= id=ZoomControl1_Form1 onkeydown=JavaScript:Navigation_ie(); ... input type=image name=ZoomControl1:Imagebutton2 onclick=if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); language=javascript id=ZoomControl1_Imagebutton2 src=../Images/Btn_GoImage.gif border=0 /nbsp; ... /form So write below code to 'click' the image button, forms = ParseResponse(urlopen(url)) form = forms[0] urlopen(form.click(ZoomControl1:Imagebutton2)) unfortunatly, however, when the code run, it just got a page which is not the one i desired ( i actually wish to get the same page as i 'click' the button). I guess that is onclick= statement cause something weird, but I do not understand it. And, in the source containing the form, i found nowhere the Page_ClientValidate() resides. What's wrong? - narke -- http://mail.python.org/mailman/listinfo/python-list
Case-insensitive dict, non-destructive, fast, anyone?
I need a dict (well, it would be optimal anyway) class that stores the keys as strings without coercing the case to upper or lower, but still provides fast lookup (i.e. uses hash table). d = CiDict([('Hi', 12),('hoho',13)]) d['hi'] 12 d.keys() ['Hi','hoho'] Note that 'Hi' preserved the case. I imagine that 'Hi' and 'hi' would need to share the same hash value in order for the lookup to be fast. Anyone have a an implementation that I could use? Quick googling only produced implementations that coerce all keys to lowercase. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
On Apr 1, 2005 8:10 PM, Erik Max Francis [EMAIL PROTECTED] wrote: Sean Kemplay wrote: You could use condition and consequent or alternative I use it You should do so cautiously, since if consequent is false, it will not behave as suspected. Not to mention that it's quite unreadable. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis Physics, as we know it, will be over in six months. -- Max Born (1928) -- http://mail.python.org/mailman/listinfo/python-list I should have mentioned that, as I have been caught out before. Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive dict, non-destructive, fast, anyone?
Ville Vainio wrote: I need a dict (well, it would be optimal anyway) class that stores the keys as strings without coercing the case to upper or lower, but still provides fast lookup (i.e. uses hash table). Store the original key together with the value and use a lowercase key for lookup. only a sketch: class MyDict: def __init__ (self): self.inner = {} def __setitem__ (self, key, value): self.inner [key.lower ()] = (key, value] def __getitem__ (self, key): realkey, realvalue = self.inner [self] return realvalue def get (self, key, default = None): try: return self [key] except KeyError: return default # or: return self.inner.get (key.lower (), (None, default)) [1] def keys (self): return [realkey for realkey, realval in self.inner.values ()] def values (self): return [realval for realkey, realval in self.inner.values )] def items (): return self.inner.values () # iterators are left as an exercise -- http://mail.python.org/mailman/listinfo/python-list
Showing errors explicitly in try... except
When using try... except... errors don't show up. Is there a way to force stderr despite using try...except? thanks, Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ method and raising exceptions
Exactly the answer I was looking for! 12 hours of straight programming tends to fog ones mind. Thanks for making it clear! Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: Combining digit in a list to make an integer
Harlin Seritt wrote: I have the following: num1 = ['1', '4', '5'] How can I combine the elements in num1 to produce an integer 145? int(''.join(num1)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Combining digit in a list to make an integer
If anyone has time, would you mind explaining the code that Dan Bishop was so kind as to point out to me: int(''.join(num1)) This worked perfectly for me, however, I'm not sure that I understand it very well. Thanks, Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting methods with similar names
Suggesting method names based on a wrong method name can be useful, but I think the smart help can be improved: it can also be useful to have a suggestion for method names on the basis on a short description (or keywords) about what I want to do to/with the object. Maybe some people here can give me some suggestions on how to do this. I think I can add a Keywords: , xxx, . final part to each docstring of the methods, so a kind of little search engine can search for the few most fitting methods based on the user text search query, and on the methods keywords+doc texts. User query example: How to rotate the object Result (a short ranked list of method names that can perform that operation): rotate, flip, pivot, mirror (Note: the query is inserted calling a help method, or something similar, etc. It doesn't require any magic.) Do you know any little search engine that can be used for this purpose? Thank you, Bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda: the Ultimate Design Flaw
Daniel Silva wrote: We think dropping FILTER and MAP is pretty uncontroversial; (filter P S) is almost always written clearer as a DO loop (plus the LAMBDA is slower than the loop). Even more so for (map F S). In all cases, writing the equivalent imperative program is clearly beneficial. How about using srfi-42 instead of those nasty do loops? It's pretty clean: (list-ec (: a lis) (* a a)) is equivalent to (map (lambda (a) (* a a)) lis) Before I discovered srfi-42, my code often had hideous things like: (append-map (lambda (item) (map (lambda (inner) (* inner inner)) (cdr item))) lis) to return (1 4 9 16 25 36 49 64 81) for a lis that's '((a 1 2 3) (b 4 5 6) (c 7 8 9))). This becomes even neater: (list-ec (: item lis) (: inner (cdr item)) (* inner inner)) Have a happy first of april! -- http://mail.python.org/mailman/listinfo/python-list
Re: Combining digit in a list to make an integer
Harlin Seritt wrote: If anyone has time, would you mind explaining the code that Dan Bishop was so kind as to point out to me: int(''.join(num1)) This worked perfectly for me, however, I'm not sure that I understand it very well. Thanks, Harlin Seritt ''.join(list of strings) is a python idiom for fast string concatenation. ''.join(num1) would give 145. The function int() is then used to convert the resulting string into an integer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Combining digit in a list to make an integer
Harlin Seritt wrote: If anyone has time, would you mind explaining the code that Dan Bishop was so kind as to point out to me: int(''.join(num1)) This worked perfectly for me, however, I'm not sure that I understand it very well. join(...) S.join(sequence) - string Return a string which is the concatenation of the strings in the sequence. The separator between elements is S. For example: ''.join(['1', '2', '3']) '123' If you don't want a separator, simply let S be the empty string (''). -- http://mail.python.org/mailman/listinfo/python-list
Spider - path conflict [../test.htm,www.nic.nl/index.html]
H! I thought I was ready with my own spider... But then there was a bug, or in other words a missing part in my code. I forget that people do this in website html: a href=http://www.nic.nl/monkey.html;is oke/a a href=../monkey.htmlerror/a a href=../../monkey.htmlerror/a So now i'm trying to fix my spider but it fails and it fails. I tryed something like this. import urlparse import string def fixPath(urlpath,deep): path='' test = urlpath.split('/',deep) for this in test: if this'' and this.count('.')==0: path=path+'/'+this return path def fixUrl2(src,url): url = urlparse.urlparse('http://'+url) src = urlparse.urlparse('http://'+src) if url[2]: thepath = fixPath(url[2],url[2].count('/')-(src[2].count('/'))) if src[1] == '..': if url[1]'': theurl = url[1]+''+thepath+''+src[2].replace('../','') print theurl fixUrl2('../monkey2.html','www.nic.nl/test/info/monkey1.html') fixUrl2('../../monkey2.html','www.nic.nl/test/info/monkey1.html') fixUrl2('../monkey2.html','www.nic.nl/info/monkey1.html') info: fixUrl2('a new link found','in this page') I hope someone knows a professional working code for this, Thanks a lot, GC-Martijn -- http://mail.python.org/mailman/listinfo/python-list
Re: Stylistic question about inheritance
Andrew Koenig [EMAIL PROTECTED] writes: Lonnie Princehouse [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] If you try this sort of inheritance, I'd recommend writing down the formal grammar before you start writing classes. Don't try to define the grammar through the inheritance hierarchy; it's too easy to accidentally build a hierarchy that can't be translated into a single-pass-parsable grammar... Understood. I was using expression trees as a contrived example, and really want to know about the Python community's stylistic preferences for defing such hierarchies that don't absolutely need a root. Oddly enough, I've just been pondering the same question (albeit for Perl, but the same reasoning applies). The only cases I've found useful thus far are: - implementation inheritance (in the case of default methods in a callback interface class): class CallbackInterface: def handleEvent(self, event): Handle an event pass def handleSignal(self, signal): Handle a signal pass This also helps to document what's expected of callback classes, even though they don't _have_ to inherit CallbackInterface (enforcing this through isinstance() in the calling class would be rude). - hierarchies of exception classes (allowing one to catch general classes of exceptions, since except implicitly uses isinstance(), rather than a specific class). Of course, Python already has a hierarchy of exceptions. I had to implement my own for Perl. From a brief skim of http://www.python.org/moin/PythonThreeDotOh it looks like interfaces _may_ be added to Python 3.0, but they sound more like (IIRC) ML's signatures and C++'s Standard Library requirements i.e. a requirement that the class implements certain functions, rather than a requirement to inherit from a particular base class. Guy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
praba kar [EMAIL PROTECTED] wrote: Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. You answered your own question; there is no ternary operator in Python. There was a major debate on this newsgroup a year or so ago on this subject, and the decision was quite clear that no such feature would be added. If you google for python ternary, you will find a huge amount of material written on the subject. -- http://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive dict, non-destructive, fast, anyone?
Daniel == Daniel Dittmar [EMAIL PROTECTED] writes: Daniel Ville Vainio wrote: I need a dict (well, it would be optimal anyway) class that stores the keys as strings without coercing the case to upper or lower, but still provides fast lookup (i.e. uses hash table). Daniel Store the original key together with the value and use a Daniel lowercase key for lookup. That's what I thought initially, but the strings take most of the space in dict and I didn't feel like doubling the size. It would be the simplest thing that could possibly work, though. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Re: Spider - path conflict [../test.htm,www.nic.nl/index.html]
I think you want urllib.basejoin(). urllib.basejoin(http://www.example.com/test/page.html;, otherpage.html) 'http://www.example.com/test/otherpage.html' pgpSOZBAEHiWi.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary: sorting the values preserving the order
Another alternative: d1 = {'a':4,'b':5,'c':1,'d':2,'e':3} il=[(v,k) for k,v in d1.items()] il.sort() -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda: the Ultimate Design Flaw
Hallchen! Daniel Silva [EMAIL PROTECTED] writes: Shriram Krishnamurthi has just announced the following elsewhere; it might be of interest to c.l.s, c.l.f, and c.l.p: http://list.cs.brown.edu/pipermail/plt-scheme/2005-April/008382.html The Fate Of LAMBDA in PLT Scheme v300 or Lambda the Ultimate Design Flaw About 30 years ago, Scheme had FILTER and MAP courtesy of Lisp hackers who missed them from their past experience. To this collection, Scheme added a lexically-scoped, properly-functioning LAMBDA. But, despite of the PR value of anything with Guy Steele's name associated with it, we think these features should be cut from PLT Scheme v300. [...] The whole text seems to be a variant of http://www.artima.com/weblogs/viewpost.jsp?thread=98196. Tsch, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest vs py.test?
Nigel Rowe [EMAIL PROTECTED] wrote: Have you seen Grig Gheorghiu's 3 part comparison of unittest, and py.test? http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-2-doctest.html http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-3-pytest-tool.html Just finished reading them now. Thanks for the pointer, they make an excellent review of the space. One thing that worries me a little is that all three seem to have advantages and disadvantages, yet none is so obviously better than the others that it stands out as the only reasonable way to do it. This means some groups will adopt one, some will adopt another, and the world will become fragmented. -- http://mail.python.org/mailman/listinfo/python-list
Re: Spider - path conflict [../test.htm,www.nic.nl/index.html]
urllib.basejoin() that's what I need :) haha what a stupid code did I made. Thanks GC-Martijn -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: BigDecimal - decimal arithmetic on very large intergers
[EMAIL PROTECTED] wrote: BigDecimal is a Python class that supports decimal arithmetic on very large integers. BigDecimal was inspired by the posting of BigDec to c.l.py by Tim Peters. BigDecimal implements all the commonly used integer methods. (It doesn't implement any of the binary/shifting operations.) It has been optimized for performance. It uses a 4x4 Toom-Cook algorithm for multiplication and a new, very fast, division algorithm. If GMPY is available, it will be automatically used. Performance examples, computing the decimal represendation of the 42nd Mersenne prime: 2**25964951 - 1 Tim Peter's posting to c.l.py: 13 minutes 41 seconds BigDecimal: 59 seconds BigDecimal w/gmpy: 10 seconds You might want to look into mxNumber (part of the egenix-mx-experimental package): http://www.egenix.com/files/python/mxNumber.html There's a C type called Integer in that package that basically wraps the GMP integer type. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 01 2005) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! -- http://mail.python.org/mailman/listinfo/python-list
Pseudocode in the wikipedia
The free wikipedia is adopting a standard pseudocode: http://en.wikipedia.org/wiki/Wikipedia_talk:Wikicode/Specification MShonle says something nice: I support the idea of wikicode. Basically I think we should present code in a Python-like language that doesn't carry so much baggage. For example, we can use English sentences (or sentence fragments) instead of requiring the reader to understand some obscure Python library. (Further, Python has the baggage that there are no block-terminators: i.e., no } or ends or fis or repeats. By adding such terminators, we can make it a lot less ambiguous to all readers.) In otherwords, we're basically right on track: removing the quirks of Python, and making it higher-level. Bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
praba kar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this There isn't one, and there won't be one unless Guido changes his mind, and that's quite unlikely. There are a number of workarounds; the most used one seems to be based on a feature of the 'and' and 'or' operators. I believe Pep 308 has a summary of the different ways you can do it, and the advantages and drawbacks of each. John Roth __ Yahoo! Messenger Show us what our next emoticon should look like. Join the fun. http://www.advision.webevents.yahoo.com/emoticontest -- http://mail.python.org/mailman/listinfo/python-list
Re: Spider - path conflict [../test.htm,www.nic.nl/index.html]
martijn I thought I was ready with my own spider... But then there was martijn a bug, or in other words a missing part in my code. martijn I forget that people do this in website html: martijn a href=http://www.nic.nl/monkey.html;is oke/a martijn a href=../monkey.htmlerror/a martijn a href=../../monkey.htmlerror/a pydoc urlparse.urljoin Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive dict, non-destructive, fast, anyone?
Ville Vainio wrote: Daniel == Daniel Dittmar [EMAIL PROTECTED] writes: Daniel Ville Vainio wrote: I need a dict (well, it would be optimal anyway) class that stores the keys as strings without coercing the case to upper or lower, but still provides fast lookup (i.e. uses hash table). Daniel Store the original key together with the value and use a Daniel lowercase key for lookup. That's what I thought initially, but the strings take most of the space in dict and I didn't feel like doubling the size. You could write a string wrapper that changes comparison and hashing. I'm not sure that this (+ 1 (Python object + instance dictionary)) would use less memory than the other proposal (+ 1 Tuple + 1 String). Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Showing errors explicitly in try... except
Harlin Seritt [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] When using try... except... errors don't show up. Is there a way to force stderr despite using try...except? If you're looking for stack traces, look at the inspect and traceback modules. They contain the tools to do just about anything you need for error reporting. Also there is a logger module somewhere so you can put the stuff somewhere permanent if you want. John Roth thanks, Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
praba kar wrote: Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this There is no ternary operator in python. There are several idioms that can be used to emulate one to a certain degree - but they are scolwed on by quite a few people. So better to not use them and just do it in a if: else: clause. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
3 weeks to go to Python-UK!
There are just three weeks to go to Python-UK! The UK Python conference is once again taking place at the Randolph Hotel in the centre of historic Oxford, as part of the ACCU conference, on 21-23 April. http://www.accu.org/conference/python.html On Tuesday 19th there's also a full day tutorial for intermediate and advanced Python programmers, given by Michele Simionato, at a fraction of the price of most professional training courses. There are just a few places remaining, so book quickly! http://www.accu.org/conference/python_tutorial.html Anyone attending the event is free to move between tracks and learn from a world-class program on patterns, agile development, Java, C++ and C# as well as Python. Best Regards, Andy Robinson Python-UK Conference chair -- http://mail.python.org/mailman/listinfo/python-list
ANNOUNCE: xsdb release with N/A support and more
The new xsdbXML_cs_java_py_01 release adds a not applicable attribute restriction and completes the same/ifknown/otherwise implementations as well as some bugfixes including a fix for a performance bug in the java implementation. The xsdb framework provides a flexible and well defined infrastructure to allow tabular data to be published, retrieved, and combined over the Internet. There are three separate implementations: a Python implementation, a C#/.NET implementation, and a java implementation. For all implementations all source code is distributed using SourceForge. Read more and download at http://xsdb.sourceforge.net Thanks, -- Aaron Watters === KIDS MAKE NUTRITIOUS SNACKS -- a real life headline http://www.anvari.org/shortjoke/Newspaper_Headlines -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda: the Ultimate Design Flaw
The Fate Of LAMBDA in PLT Scheme v300 or Lambda the Ultimate Design Flaw Why drop LAMBDA? Why not? Isn't all code eventually anonymous and relocatable? -- http://mail.python.org/mailman/listinfo/python-list
Re: StopIteration in the if clause of a generator expression
Peter Otten wrote: To confuse a newbies and old hands alike, Bengt Richter wrote: got me for one:) To make it a bit clearer, a StopIteration raised in a generator expression silently terminates that generator: *any* exception raised from a generator, terminates the generator jfj -- http://mail.python.org/mailman/listinfo/python-list
Re: New to programming question
Bengt Richter wrote: On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney [EMAIL PROTECTED] wrote: Oh goddammmni. I seem to be doing this a lot today. Look below for the extra addition to the code I posted. Joal Heagney wrote: Here's my contribution anycase: count = 0 # Get first input name = raw_input(Guess my name: ) # Give the sucker two extra goes while count 2: # Check the value of name if name == 'Ben': print You're right! break else: name = raw_input(Try again: ) # Here's the bit I missed out. count += 1 # Of course, we haven't checked the sucker's last guess # so we have to do that now. if count == 2: if name == 'Ben': print You're right! else: print No more tries for you!!! Hope this helps. Joal G. Need something more straightforward, e.g., a wrapped one-liner: def guess(n=3): print (You're right!, 'No more tries for you!!!')[n-1 in ...(x for x in xrange(n) for t in [raw_input('Guess my name: ')=='Ben'] ...if not t or iter([]).next())] Okay, now in my opinion, that's just too complex to give to a newbie as a suggested implementation. :) Joal -- http://mail.python.org/mailman/listinfo/python-list
Unzipping Files
Hello- I am trying to read a file from a zip archive. I have read the documentation on zipfile and can read the names of the files in the archive and the length of each file, but do not see how to get to the actual data from any given file. This is probably so simple that it hurts, so take it easy on me if you please...I just don't see it and have a deadline rushing towards me. How do I read the data from a file in a zip archive? Thanks! --greg -- Greg Lindstrom 501 975.4859 (office) Senior Programmer501 219-4455 (fax) NovaSys Health [EMAIL PROTECTED] Little Rock, Arkansas We are the music makers, and we are the dreamers of dreams. W.W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unzipping Files
On Apr 1, 2005 8:14 PM, Greg Lindstrom [EMAIL PROTECTED] wrote: How do I read the data from a file in a zip archive? http://www.devshed.com/c/a/Python/Python-UnZipped Regards, -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info -- http://mail.python.org/mailman/listinfo/python-list
Looking for Benchmarklets to improve pyvm
Hi. pyvm is a program that can run python 2.4 bytecode and most of the times produce the expected output. See http://students.ceid.upatras.gr/~sxanth/ I'm collecting small testlets to benchmark it, discover bottlenecks and improve it. They should be small and not use any crazy modules. Only [sys, os, itertools, thread, threading, math, random] for now. Basically, stuff that has appeared in c.l.py will be great (like xah lee's partition list be equivalence, etc) Send! Stelios -- http://mail.python.org/mailman/listinfo/python-list
Re: Unzipping Files
Use something like: import zipfile zfile=zipfile.ZipFile(zipfilename,'r') contents=zfile.read(filenametoread) Stripped out of a working program, but not tested. -Larry Bates Greg Lindstrom wrote: Hello- I am trying to read a file from a zip archive. I have read the documentation on zipfile and can read the names of the files in the archive and the length of each file, but do not see how to get to the actual data from any given file. This is probably so simple that it hurts, so take it easy on me if you please...I just don't see it and have a deadline rushing towards me. How do I read the data from a file in a zip archive? Thanks! --greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda: the Ultimate Design Flaw
On Thu, 31 Mar 2005 23:30:42 -0800, Erik Max Francis wrote: Daniel Silva wrote: Shriram Krishnamurthi has just announced the following elsewhere; it might be of interest to c.l.s, c.l.f, and c.l.p: http://list.cs.brown.edu/pipermail/plt-scheme/2005-April/008382.html April Fool's Day again, eh? Yes and no. In the Python community, we're taking all of that pretty seriously. The scheme community may not seriously be thinking of getting rid of those things, but it's hardly impossible that some people think it might be better off without it. -- http://mail.python.org/mailman/listinfo/python-list
Re: StopIteration in the if clause of a generator expression
Peter Otten wrote: To confuse a newbies and old hands alike, Bengt Richter wrote: Need something more straightforward, e.g., a wrapped one-liner: def guess(n=3): print (You're right!, 'No more tries for you!!!')[n-1 in ...(x for x in xrange(n) for t in [raw_input('Guess my name: ')=='Ben'] ...if not t or iter([]).next())] ... guess() To make it a bit clearer, a StopIteration raised in a generator expression silently terminates that generator: def stop(): raise StopIteration ... list(i for i in range(10) if i 5 or stop()) [0, 1, 2, 3, 4] In a list comprehension, on the other hand, it is propagated: [i for i in range(10) if i 5 or stop()] Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 1, in stop StopIteration Is that an intentional difference? Very interesting. I'm not sure if the designers even considered this particular subtlety. Why it happens is pretty plain. In the generator expression case, the generator expression does propogate the StopIteration, but list() traps it. List comprehensions are internally treated as a for-loop (kind of), which doesn't trap StopIteration. Maybe it should. The list comprehension [ x for x in y ] is currently treated as equivalent to the following, with byte-code optimizations: . _ = [] . for x in y: . _.append(x) Perhaps it ought to be equivalent to: . _ = [] . try: . for x in y: . _.append(x) . except StopIteration: . pass However, I would guess the Python gods wouldn't approve of this use of StopIteration, and so would make no sacrifices to get it. Nevertheless, it seems likely to be how a list comprehension would behave in Python 3.0, so maybe we should do it. -- CARL BANKS -- http://mail.python.org/mailman/listinfo/python-list
Re: class attributes and inner classes in C extensions
I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = foobar How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? O.k. I found it out now, and in order to improve the knwoledge base of the mailing list, I will answer my question myself. The PyTypeObject structure has a field tp_dict that holds the dictionary of the class object. You can initialize it with a dictionary that holds class attributes. If you provide a custom dictiomary, you must do so _before_ PyType_Ready() is called, because PyType_Ready adds other entries to this dictionary. This is my C extension of the above. It works great for me: static PyTypeObject FooType = { /* ... snip ... */ 0, // tp_dict /* ... snip ... */ }; static PyTypeObject FooBarType = { /* ... snip ... */ }; PyMODINIT_FUNC inithyper(void) { /* the following lines add class attributes to the types tp_dict: */ FooType.tp_dict = PyDict_New(); PyDict_SetItemString(FooBarType,Bar,(PyObject *)FooBarType); PyDict_SetItemString(FooBarType,spam,PyString_FromString(foobar)); PyObject* m; if (PyType_Ready(hFooType) 0) return; if (PyType_Ready(hFooBarType) 0) return; m = Py_InitModule3(my_module, NULL, some documentation); Py_INCREF(FooType); PyModule_AddObject(m, Foo, (PyObject *)FooType); Py_INCREF(hyper_FooBarType); PyModule_AddObject(m, Bar, (PyObject *)FooBarType); } Documentation for tp_dict can be found in the API: http://docs.python.org/api/type-structs.html - harold - -- 2x2 = grün -- Heinz von Foerster -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest vs py.test?
In my mind, practicing TDD is what matters most. Which framework you choose is a function of your actual needs. The fact that there are 3 of them doesn't really bother me. I think it's better to have a choice from a small number of frameworks rather than have no choice or have a single choice that might not be the best for your specific environment -- provided of course that this doesn't evolve into a PyWebOff-like nightmare :-) Grig -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
John Roth wrote: praba kar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this There isn't one, and there won't be one unless Guido changes his mind, and that's quite unlikely. Au contraire, mon frere: There is a ternary operator in Python (fairly ill-documented) Its name is partial polynomial eval. As is traditional in implementing ternary operations in computer languages, the name of the operator does not show up anywhere in the code, so many people don't realize they are using it. Here is an example of the ppe used to evaluate a cubic, using the ternary operator three times in a single statement: def cubic(x, a, b, c, d): return ((a * x + b) * x + c) * x + d As you may be able to guess, the more common name is *+, and it is a nice self-documenting operator (it behaves just like the primitives). Originally the DEC Vax provided this as a vectorized opcode, which is where Python got the idea. You probably don't see it since you aren't doing much engineering work. --Scott David Daniels [EMAIL PROTECTED] -- No truth has been harmed by this April Fool's post. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: property and virtuality
harold fellermann [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I asked this question some time ago, but as I got no answer, so I just try it a second time. This did get out, but I can't answer except to suggest looking at code for other C extension modules. Nested (inner) classes are fairly rare, but I presume that once you know how to add attributes in general, you add class as an attribute in the same way you would add an int, etc, as an attribute. (And if I am wrong, you should certainly get another response '-). Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: StopIteration in the if clause of a generator expression
[Peter Otten] a StopIteration raised in a generator expression silently terminates that generator: def stop(): raise StopIteration ... list(i for i in range(10) if i 5 or stop()) [0, 1, 2, 3, 4] In a list comprehension, on the other hand, it is propagated: [i for i in range(10) if i 5 or stop()] Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 1, in stop StopIteration Is that an intentional difference? I would call it an unfortunate assymmetry -- one the never comes up unless you're up to no good ;-) In a way, both behave identically. They both raise StopIteration. In the case of the generator expression, that StopIteration is intercepted by the enclosing list() call. That becomes obvious if you write a pure python equivalent for list: def lyst(s): it = iter(s) result = [] try: while 1: result.append(it.next()) except StopIteration:# guess who trapped StopIter return result Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest vs py.test?
[Roy Smith [EMAIL PROTECTED]] One thing that worries me a little is that all three seem to have advantages and disadvantages, yet none is so obviously better than the others that it stands out as the only reasonable way to do it. This means some groups will adopt one, some will adopt another, and the world will become fragmented. Worry is a natural thing for someone with panix in their email address ;-) FWIW, the evolution of py.test is to also work seemlessly with existing tests from the unittest module. the world diversifies, the world congeals, Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ method and raising exceptions
Vikram wrote: I can't use 'break' or 'continue' in a class method, nor can I return a boolean value from __init__() to check for errors within the for-loop. How would I be able to stop the current iteration and continue with the next after reporting an error? maybe i don't fully understand your qn but why don't you let __init__ of your class raise an exception and then catch it in the outer for loop and continue. something like: for i in ... try: foo() except: except (ValueError, TypeError), error: continue Use something like the above, (always expect certain kinds of errors) lest you accidentally capture an real attempt to stop the program such as the exception a Control-C causes. -Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Combining digit in a list to make an integer
On 1 Apr 2005 03:21:12 -0800, Harlin Seritt [EMAIL PROTECTED] wrote: num1 = ['1', '4', '5'] How can I combine the elements in num1 to produce an integer 145? num1 = ['1', '4', '5'] int(''.join(num1)) 145 .Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ -- http://mail.python.org/mailman/listinfo/python-list
Shelve DBRunRecoveryError
Can anyone help with this error message when using Shelve : Python 2.4. Traceback (most recent call last): File C:\Python24\CollectB\dataparser.py, line 743, in -toplevel- base.create() File C:\Python24\CollectB\dataparser.py, line 252, in create self.dataStore[i] = v File C:\Python24\lib\shelve.py, line 130, in __setitem__ self.dict[key] = f.getvalue() File C:\Python24\lib\bsddb\__init__.py, line 218, in __setitem__ self.db[key] = value DBRunRecoveryError: (-30978, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: Invalid argument') Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: property and virtuality
Laszlo Zsolt Nagy [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]... My problem is about properties and the virtuality of the methods. I would like to create a property whose get and set methods are virtual. I had the same problems in Delphi before and the solution was the same. I created a private _get method and a public get method. The former one will call the latter. [...] I cannot override C2._getname instead, because c2.name would print 'Test2 instead of lala. Clearly, the property stores a reference to the get and set methods and it is not possible to have it use the new methods. Creating a new property is the worst - need to duplicate code and also C3.name is C1.name returns False. :-) It is not a big problem because I found the solution just I wonder if there is a better way to virtualize property get/set functions. Alex Martelli has demonstrated the same technique to fix this disturbing property behavior during one of its talk at Pycon 2005: http://www.python.org/pycon/2005/papers/36/ (slides p.78) ... from this I infer that you found the best fix available ;) Regards, Sébastien -- http://mail.python.org/mailman/listinfo/python-list
Re: string goes away
OK, you won. I read in an (regretably old) guidline for improving Python's performance that you should prefer map() compared to list comprehensions. Apparently the performance of list comprehensions has improved a lot, which is great. (Or the overhead of calling map() got too big, but I hope this is not the case.) So, what is the purpose of map()? Should it too be deprecated? Andreas Skip Montanaro wrote: Andreas Yeeh, I was expecting something like that. The only reason to Andreas use map() at all is for improving the performance. That is Andreas lost when using list comprehensions (as far as I know). So, Andreas this is *no* option for larger jobs. Did you test your hypothesis? % python -m timeit -s 'lst = (abc*10).split() ; import string' 'map(string.upper, lst)' 10 loops, best of 3: 9.24 usec per loop % python -m timeit -s 'lst = (abc*10).split()' '[s.upper() for s in lst]' 10 loops, best of 3: 4.18 usec per loop % python -m timeit -s 'lst = (abc*100).split() ; import string' 'map(string.upper, lst)' 10 loops, best of 3: 16.1 usec per loop % python -m timeit -s 'lst = (abc*100).split()' '[s.upper() for s in lst]' 10 loops, best of 3: 10.8 usec per loop % python -m timeit -s 'lst = (abc*1000).split() ; import string' 'map(string.upper, lst)' 1 loops, best of 3: 72.7 usec per loop % python -m timeit -s 'lst = (abc*1000).split()' '[s.upper() for s in lst]' 1 loops, best of 3: 67.7 usec per loop % python -m timeit -s 'lst = (abc*1).split() ; import string' 'map(string.upper, lst)' 1000 loops, best of 3: 844 usec per loop % python -m timeit -s 'lst = (abc*1).split()' '[s.upper() for s in lst]' 1000 loops, best of 3: 828 usec per loop % python -m timeit -s 'lst = [abc*10]*10 ; import string' 'map(string.upper, lst)' 1 loops, best of 3: 42.7 usec per loop % python -m timeit -s 'lst = [abc*10]*10' '[s.upper() for s in lst]' 1 loops, best of 3: 26.5 usec per loop % python -m timeit -s 'lst = [abc*10]*100 ; import string' 'map(string.upper, lst)' 1000 loops, best of 3: 376 usec per loop % python -m timeit -s 'lst = [abc*10]*100' '[s.upper() for s in lst]' 1000 loops, best of 3: 230 usec per loop % python -m timeit -s 'lst = [abc*10]*1000 ; import string' 'map(string.upper, lst)' 100 loops, best of 3: 3.72 msec per loop % python -m timeit -s 'lst = [abc*10]*1000' '[s.upper() for s in lst]' 100 loops, best of 3: 2.23 msec per loop The above results are using Python CVS (aka 2.5a0). Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: BigDecimal - decimal arithmetic on very large intergers
M.-A. Lemburg wrote: [EMAIL PROTECTED] wrote: BigDecimal is a Python class that supports decimal arithmetic on very large integers. BigDecimal was inspired by the posting of BigDec to c.l.py by Tim Peters. BigDecimal implements all the commonly used integer methods. (It doesn't implement any of the binary/shifting operations.) It has been optimized for performance. It uses a 4x4 Toom-Cook algorithm for multiplication and a new, very fast, division algorithm. If GMPY is available, it will be automatically used. Performance examples, computing the decimal represendation of the 42nd Mersenne prime: 2**25964951 - 1 Tim Peter's posting to c.l.py: 13 minutes 41 seconds BigDecimal: 59 seconds BigDecimal w/gmpy: 10 seconds You might want to look into mxNumber (part of the egenix-mx-experimental package): http://www.egenix.com/files/python/mxNumber.html There's a C type called Integer in that package that basically wraps the GMP integer type. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 01 2005) Python/Zope Consulting and Support ... http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! I have used mxNumber in the past. This library uses super digits with hundreds / thousands of decimal digits and then builds builds multiplication and division on those. The original motivation was that the conversion time to / from decimal string format is O(n) instead of O(n^2). Using just native Python long support, the 4-way Toom-Cook multiplication algorithm is faster than the built-in multiplication when the numbers are several hundred thousand digits long. On my machine, it is roughly twice as fast when multiplying one million digit numbers. (The 4-way Toom-Cook is O(n^~1.4) versus O(n^~1.585) for the Karatsuba multiplication in Python.) The division algortihm in BigDecimal is effectively O(n^~1.4) also. Using just native Python long support, the division algorithm is faster than the built-in division algorithm when the numbers are several tens of thousands digits long. Interestingly, BigDecimal can do division faster than GMP 3.1.x with numbers approximately 10 million digits in length. BigDecimal is faster than GMP 4.1.4 with numbers of approximately 1 million digits in length. (GMP 4 is faster for small, ~10,000 digits, than GMP 3, but grows more quickly.) casevh -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest vs py.test?
On Fri, 01 Apr 2005 16:42:30 +, Raymond Hettinger wrote: FWIW, the evolution of py.test is to also work seemlessly with existing tests from the unittest module. Is this true now, or is this planned? I read(/skimmed) the docs for py.test when you linked to the project, but I don't recall seeing that. Certainly some of the features made me drool but I have an investment in unittest. If I can relatively easily port them over, I'd love to use py.test. (I don't care about a small per-file change, it'd probably be one I can automate anyhow. But I can't afford to re-write every test.) I didn't see anything like this in the docs, but I may have missed it. That'd be cool. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda: the Ultimate Design Flaw
[Sunnan] [...] for Pythons ideal of having one canonical, explicit way to program. No doubt it once was true, but I guess this ideal has been abandoned a few years ago. My honest feeling is that it would be a mis-representation of Python, assertng today that this is still one of the Python's ideals. -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest vs py.test?
From what I know, the PyPy guys already have a unittest-to-py.test translator working, but they didn't check in the code yet. You can send an email to py-dev at codespeak.net and let them know you're interested in this functionality. Grig -- http://mail.python.org/mailman/listinfo/python-list
Re: Case-insensitive dict, non-destructive, fast, anyone?
On 01 Apr 2005 15:55:58 +0300, Ville Vainio [EMAIL PROTECTED] wrote: Daniel == Daniel Dittmar [EMAIL PROTECTED] writes: Daniel Ville Vainio wrote: I need a dict (well, it would be optimal anyway) class that stores the keys as strings without coercing the case to upper or lower, but still provides fast lookup (i.e. uses hash table). Daniel Store the original key together with the value and use a Daniel lowercase key for lookup. That's what I thought initially, but the strings take most of the space in dict and I didn't feel like doubling the size. It would be the simplest thing that could possibly work, though. Try access the keys indirectly though another dictionary. That way you don't have to change the original. Lkeys = {} for k dict.keys(): Lkeys[ k.lower] = dict[k] Then use: value = dict[ Lkeys[ key.lower() ] ] To get your value from the original dictionary. Watch out for duplicate keys in differing case in the original dict. Ron -- http://mail.python.org/mailman/listinfo/python-list
numeric module
Hello, What's the problem with this code? I get the following error message: File test.py, line 26, in test print tbl[wi][bi] IndexError: index must be either an int or a sequence ---code snippet from Numeric import * tbl = zeros((32, 16)) def test(): val = testme() wi = crc 4 bi = crc 0xFL print wi print bi print tbl[wi][bi] def testme(): val = 0xFFL val = 23 return val if __name__ == '__main__': test() Thanks, -SB -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for Benchmarklets to improve pyvm
Hi Stelios, Newbie here (new to the language and scripting in general). I'm trying to figure out what you mean by bytecode. Do you mean a virtual python environment that can be hosted by any anonymous operating system? For example, you want to run Python programs on BEOS so you crank up its version of PYVM and load a Python source code and run it? Or do you mean you want Python that's been compiled down to something like p-code on my machine, then you receive the p-code that you can expect to run? Is pyvm your own work? Has anyone computed the digits of pi (3.14159265) in Python? That might be a good application for string processing. Jim in Indiana USA -- http://mail.python.org/mailman/listinfo/python-list
Re: Showing errors explicitly in try... except
Harlin Seritt wrote: When using try... except... errors don't show up. Is there a way to force stderr despite using try...except? force, no. The stderr stuff is done by an unhandled exception handler that is at the very top level, so if you catch the exception, it will never see it to print it. Doing this will probably suffice, however: import traceback try: 1/0 # one should avoid non-specific exception catching # in most cases, but this is an example: except: traceback.print_exc() -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Pseudocode in the wikipedia
[EMAIL PROTECTED] wrote: (Further, Python has the baggage that there are no block-terminators: i.e., no } or ends or fis or repeats. By adding such terminators, we can make it a lot less ambiguous to all readers.) In otherwords, we're basically right on track: removing the quirks of Python, and making it higher-level. Heh heh... good joke for April 1. Clearly, calling the absence of something baggage is intended to be humorous... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
On Fri, 1 Apr 2005 08:24:42 +0100 (BST), praba kar [EMAIL PROTECTED] wrote: Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this __ Yahoo! Messenger Show us what our next emoticon should look like. Join the fun. http://www.advision.webevents.yahoo.com/emoticontest I've used boolean opperations to do it. result = (v == value) * first + (v != value) * second Same as: if v == value: result = first else: result = second Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda: the Ultimate Design Flaw
Jeremy Bowers [EMAIL PROTECTED] writes: On Thu, 31 Mar 2005 23:30:42 -0800, Erik Max Francis wrote: Daniel Silva wrote: Shriram Krishnamurthi has just announced the following elsewhere; it might be of interest to c.l.s, c.l.f, and c.l.p: http://list.cs.brown.edu/pipermail/plt-scheme/2005-April/008382.html April Fool's Day again, eh? Yes and no. In the Python community, we're taking all of that pretty seriously. The Python community takes many things pretty seriously. Whitespace and Guido come to mind. -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary: sorting the values preserving the order
Rakesh [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] This gets a list sorted by the keys. That is all you *can* get (with the list keys being the dict values). How would I get a revised dictionary sorted by its values. You can't. A dictionary is not sorted. The print order is arbitrary and not controllable. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric module
In function test(), Read wi and bi as: wi = val 4 bi = val 0xFL -SB -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric module
I don't know much here...but is there an assumption you're making about the machine word size to be greather than 24 bits? Also, more to the point, does the function zeros() instantiate a two-dimensional table? If so, does it populate the table with any values? The error looks like tbl[ ][ ] doesn't get defined. Thanks for patience! -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda: the Ultimate Design Flaw
Jeremy Bowers wrote: Yes and no. In the Python community, we're taking all of that pretty seriously. The scheme community may not seriously be thinking of getting rid of those things, but it's hardly impossible that some people think it might be better off without it. Lambda is a primitive in Scheme; in some implementations of scheme it's used to implement things like temporary variables (let), sequences (begin) and looping (named let/letrec). Python has other ways of doing these things; and removing things that has been obsoleted or superfluous makes sense, for Pythons ideal of having one canonical, explicit way to program. Having a few very abstract primitives that the rest of the language can theoretically be built upon is one of the reasons why Scheme/Lisp can work as a programmable programming language. Scheme is like Go - a few abstract rules that can be combined in endless, sprawling ways. Python is like (hmm, better let some pythonista answer this. I'm thinking of a game with a clear thematical connection (like Monopoly or The Creature that Ate Sheboygan) and a few explicit rules that combine in ways that is supposed to have a clear, readable, consistent result). Maybe shogi? (I don't usually read comp.lang.python and I really don't want to offend anyone. My apologies if this post is either annoyingly obvious (and thus contains only stuff that's been said a million times), or totally wrong.) Sunnan -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric module
The table initializes to a 2 dimensional with zeros. -SB -- http://mail.python.org/mailman/listinfo/python-list
Re: class attributes and inner classes in C extensions
harold fellermann [EMAIL PROTECTED] writes: I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = foobar How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? O.k. I found it out now, and in order to improve the knwoledge base of the mailing list, I will answer my question myself. The PyTypeObject structure has a field tp_dict that holds the dictionary of the class object. You can initialize it with a dictionary that holds class attributes. If you provide a custom dictiomary, you must do so _before_ PyType_Ready() is called, because PyType_Ready adds other entries to this dictionary. I think you could as well, after PyType_Ready() is called, set it yourself with PyObject_SetAttrString(FooType, Bar, FooBarType); You *may* have to cast the FooType and FooBarType to (PyObject *), to avoid compiler warnings. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric module
[EMAIL PROTECTED] wrote: Hello, What's the problem with this code? I get the following error message: File test.py, line 26, in test print tbl[wi][bi] IndexError: index must be either an int or a sequence ---code snippet from Numeric import * tbl = zeros((32, 16)) def test(): val = testme() wi = crc 4 bi = crc 0xFL print wi print bi print tbl[wi][bi] def testme(): val = 0xFFL val = 23 return val if __name__ == '__main__': test() Hmm... I can't reproduce this with numarray. Maybe this only exists in Numeric? Are you sure that the code here is what produced the error? py import numarray as na py tbl = na.zeros((32, 16)) py def test(): ... val = testme() ... wi = val 4 ... bi = val 0xFL ... print wi ... print bi ... print tbl[wi][bi] ... py def testme(): ... val = 0xFFL ... val = 23 ... return val ... py test() 0 1 0 STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator in Python
praba kar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this A unary operator has one operand; a binary operator has two operands; a ternary operator has three operands. Python has none built-in, although one can 'synthesize' all sorts of ternary operators by combining two binary operators, with the operand of one being the result of the other. However, people often don't think of such combinations as being such. Since C has one builtin ternary 'operator' (if-else), the term 'ternary operator' is too often used as a synonym for that particular example of a ternary operator. Others have referred you to discussions of if-else expressions in Python. Ironically, if one thinks of or defines an operator as being a function called without parenthesis, then C's ';:' and Python's 'and..or' are not really ternary operators but flow control expressions equivalent in effect to certain if/else statement pairs. That is because some of the operands may not be evaluated. That is also why there are no special methods corresponding to 'and' and 'or'. They are directly compiled to conditional code with no a function call corresponding to the 'operator'. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Decorater inside a function? Is there a way?
I'm trying to figure out how to test function arguments by adding a decorator. @decorate def func( x): # do something return x This allows me to wrap and replace the arguments with my own, but not get the arguments that the original function received. To do that I would need to put the decorator inside the function. def func( x): @decorate # doc something return x Then I could use @decorators to check the function input for condition, ranges, and or types. Is there a equivalent way to do that? Also can I use @decorate with assert? Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric module
Thanks Steve. There's a problem with Numeric array. I tried with numarray and it works fine. -SB -- http://mail.python.org/mailman/listinfo/python-list
Re: that is it is not it (logic in Python)
F. Petitjean [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I want to know if iter(iterator) returns always its argument (when argument is an iterator) By the strict definition of iterator (versus iterable) that requires that as a condition to be an iterator, then yes. If you use a looser definition of iterator, then perhaps not. iterable = range(10) it = iter(iterable) that = iter(it) that is it True# Good! that is it is not it This is equivalent to '(that is it) and (it is not it)' which is clearly false. False # What ? Reread the ref manual on chained comparison operators. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: class attributes and inner classes in C extensions
I think you could as well, after PyType_Ready() is called, set it yourself with PyObject_SetAttrString(FooType, Bar, FooBarType); You *may* have to cast the FooType and FooBarType to (PyObject *), to avoid compiler warnings. I tried this. Its shorter and and works fine, too. thanks for the proposal. - harold - -- I wish there was a knob on the TV to turn up the intelligence. There's a knob called brightness, but it doesn't seem to work. -- Gallagher -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric module
I cannot import numarray and I cannot import numeric using python 2.3.3 Where would I find an equivalent definition for zeros()? Anyway, is there supposed to be something that sets the value of elements of tbl to values other than zero? Not that the question has anything to do with Shama's problem (recognizing tbl as a two-dimensional array). -- http://mail.python.org/mailman/listinfo/python-list
how to close a gzip.GzipFile?
Hello list, gzip documentation states that calling the .close() method on a GzipFile doesn't really close it. If I'm really through with it, what's the best way to close it? I'm using Python2.2 (but the gzip module doesn't seem to be any different from 2.4). Here's my code snippet, if it's relevant: oldfileobj= file(oldfile, 'r') oldmd5 = md5.new() tellold = 0 tellnew = 1 while tellold != tellnew: line = oldfileobj.readline() tellold = tellnew tellnew = oldfileobj.tell() oldmd5.update(line) At this point, I'm finished reading the file, and would like to properly close it. Should I just del oldfileobj? Also, while I'm asking, does anyone know a better way to iterate through a gzipped file? The gzip module doesn't support iteration, nor xreadlines. I need to avoid reading the entire file contents into memory, so I can't use for line in oldfileobj.readlines() Thanks for the pointers. Justin Guerin -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorater inside a function? Is there a way?
On Fri, 01 Apr 2005 18:30:56 +, Ron_Adam wrote: I'm trying to figure out how to test function arguments by adding a decorator. The rest of your message then goes on to vividly demonstrate why decorators make for a poor test technique. Is this an April Fools gag? If so, it's not a very good one as it's quite in line with the sort of question I've seen many times before. I have a hammer, how do I use it to inflate my tire? Assuming you're serious, why not use one of the many testing technologies actually designed for it, and tap into the associated body of knowledge on how to accomplish various tasks? Start with what you're trying to do, then work on how to do it. -- http://mail.python.org/mailman/listinfo/python-list